我想总结30天Date()
对象,我使用的JavaScript Date()
和设定新的日期与.setDate(.getDate()+30)
,似乎月份已经更新,当您与console.log()
但是当打印我试图获取值,JavaScript的日期()和天而不是月
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
console.log(myDate); // will show 1 month ahead
console.log("Next Month (wrong): " + myDate.getMonth()); // will thow this month! why???
var dateData = {
'day':(myDate.getDate() < 10) ? "0" + myDate.getDate() : myDate.getDate(),
'month':(myDate.getMonth() < 10) ? "0" + myDate.getMonth() : myDate.getMonth(),
'year':myDate.getFullYear()
} ;
console.log(dateData.year + "-" + dateData.month + "-" + dateData.day) ;
// it sum date but not month
PS:今天是8月28日起30天应该是07 就会在控制台输出:
Date 2017-09-27T18:07:56.101Z Scratchpad/3:14:1
Next Month (wrong): 8 Scratchpad/3:15:1
2017-08-27 // this should print 2017-09-27 but the month still 08
有什么不对?这是一个JavaScript错误或程序员混乱?
亚当的答案是正确的,但在一个侧面说明...别改变Date对象。不要。只要做一个新的。帮你一个忙,假装日期没有安装者。 –
我同意@JaredSmith。使用像https://momentjs.com/ – Adam
@ JaredSmith这样的库会更好 - 我认为这不是一个好建议,您需要用合理的参数来备份这些断言。 – RobG