2017-08-28 32 views
-1

我想总结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错误或程序员混乱?

+1

亚当的答案是正确的,但在一个侧面说明...别改变Date对象。不要。只要做一个新的。帮你一个忙,假装日期没有安装者。 –

+0

我同意@JaredSmith。使用像https://momentjs.com/ – Adam

+0

@ JaredSmith这样的库会更好 - 我认为这不是一个好建议,您需要用合理的参数来备份这些断言。 – RobG

回答

0

getMonth()函数返回值从0到11

+0

这是不同于现有的答案....怎么样?它甚至链接到相同的文档。 –

+0

够公平的。发布前我没有发现答案。 –

相关问题