Kan*_*ela 207 javascript date
我想在JavaScript中添加几个月的日期.
例如:我正在插入日期06/01/2011(格式mm/dd/yyyy),现在我想在这个日期添加8个月.我想要结果02/01/2012.
因此,当添加月份时,年份也可能会增加.
Dan*_*pov 230
从这里:
var newDate = new Date(date.setMonth(date.getMonth()+8));
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 160
将您的日期拆分为年,月和日组件,然后使用日期:
var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);
Run Code Online (Sandbox Code Playgroud)
日期将负责确定年份.
Jaz*_*ret 93
我查看了datejs并删除了将日期添加到日期处理边缘情况(闰年,更短的月份等)所需的代码:
Date.isLeapYear = function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};
Date.getDaysInMonth = function (year, month) {
return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
Date.prototype.isLeapYear = function () {
return Date.isLeapYear(this.getFullYear());
};
Date.prototype.getDaysInMonth = function () {
return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};
Date.prototype.addMonths = function (value) {
var n = this.getDate();
this.setDate(1);
this.setMonth(this.getMonth() + value);
this.setDate(Math.min(n, this.getDaysInMonth()));
return this;
};
Run Code Online (Sandbox Code Playgroud)
这将为任何应处理边缘情况的javascript日期对象添加"addMonths()"函数.感谢Coolite Inc!
使用:
var myDate = new Date("01/31/2012");
var result1 = myDate.addMonths(1);
var myDate2 = new Date("01/31/2011");
var result2 = myDate2.addMonths(1);
Run Code Online (Sandbox Code Playgroud)
- >> newDate.addMonths - > mydate.addMonths
result1 ="2012年2月29日"
result2 ="2011年2月28日"
Ale*_*lex 14
我强烈建议你看看datejs.使用它的api,它可以简单地添加一个月(以及许多其他日期功能):
var one_month_from_your_date = your_date_object.add(1).month();
Run Code Online (Sandbox Code Playgroud)
有什么好处的datejs是它处理边缘情况,因为从技术上讲,你可以使用本机Date对象及其附加方法来做到这一点.但是你最终会将头发拉到边缘的情况下,这datejs已经照顾好了你.
加上它是开源的!