在JavaScript中将日期添加到日期 [英] Adding months to a Date in JavaScript
问题描述
可能重复:
Javascript函数将X个月添加到日期
我想在用户输入结束日期添加2个月。如何在结束日期添加2个月并显示?
I'd like to add 2 months to a user-input end date. How can I add 2 months to the end date and display it?
/**
* Click "Cal" on end date
*/
function getEndDate() {
if(!document.getElementById('startdate').value.length) {
alert("Start date must be set first.");
}
else {
prevEndDate = document.getElementById('enddate').value;
displayCalendar(document.forms[0].enddate,'yyyy/mm/dd',
document.getElementById('enddatebutton'));
}
}
/**
* Click "Cal" on expiry date
*/
function getExpiryDate() {
if(!document.getElementById('enddate').value.length) {
alert("End date must be set first.");
}
else {
prevExpiryDate = document.getElementById('expirydate').value;
displayCalendar(document.forms[0].expirydate,'yyyy/mm/dd',
document.getElementById('expirydatebutton'));
}
}
任何帮助表示赞赏。谢谢!
Any help is appreciated. Thanks!
推荐答案
您需要获得添加月份的业务规则。简单的解决方案是:
You need to get business rules for adding months. The simple solution is:
function addMonths(dateObj, num) {
return dateObj.setMonth(dateObj.getMonth() + num);
}
然而,这将改变7月31日至9月31日,将转换为10月1日。此外,1月31日加1个月是2月31日,根据是否是闰年,将转换为3月2日或3日。
However, that will change 31 July to 31 September, which will be converted to 1 October. Also, 31 January plus 1 month is 31 February which will be converted to 2 or 3 March depending on whether it's a leap year or not.
您可能会期望第一个9月30日,第二个是2月28日或29日(取决于是否是闰年)。
You might expect the first to be 30 September and the second to be 28 or 29 February (depending on whether it's a leap year or not).
因此,如果你想要结束月份的话,你需要做类似的事情:
So if you want "end of months" be observed, you need to do something like:
function addMonths(dateObj, num) {
var currentMonth = dateObj.getMonth() + dateObj.getFullYear() * 12;
dateObj.setMonth(dateObj.getMonth() + num);
var diff = dateObj.getMonth() + dateObj.getFullYear() * 12 - currentMonth;
// If don't get the right number, set date to
// last day of previous month
if (diff != num) {
dateObj.setDate(0);
}
return dateObj;
}
但请与负责业务规则的人核实这是他们想要的。
But check with whoever is responsible for the business rules that that is what they want.
以上情况很好,但是为了回应McShaman的评论,这里有一个更简单的版本检查月份翻转:
The above works well, but in response to McShaman's comment here is a version with a simpler check for the month roll–over:
function addMonths(date, months) {
var d = date.getDate();
date.setMonth(date.getMonth() + +months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
// Add 12 months to 29 Feb 2016 -> 28 Feb 2017
console.log(addMonths(new Date(2016,1,29),12).toString());
// Subtract 1 month from 1 Jan 2017 -> 1 Dec 2016
console.log(addMonths(new Date(2017,0,1),-1).toString());
// Subtract 2 months from 31 Jan 2017 -> 30 Nov 2016
console.log(addMonths(new Date(2017,0,31),-2).toString());
// Add 2 months to 31 Dec 2016 -> 28 Feb 2017
console.log(addMonths(new Date(2016,11,31),2).toString());
这篇关于在JavaScript中将日期添加到日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!