简体   繁体   中英

Date() .setDate() inconsistent behaviour

According to

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate

I should expect that setDate() in code

var now = new Date();
now.setDate(0);

will change now to the last day of the previous month.

It means I should be able to do something like this:

now.setDate(0).setDate(1)

to get the date of the first day of the previous month.

But id doesn't work like that.

var now = new Date();
console.log(now)
// FF 24: Date {Wed Jul 09 2014 16:35:49 GMT+0100 (IST)}

now.setDate(0);
console.log(now)
// FF 24: Date {Mon Jun 30 2014 16:35:49 GMT+0100 (IST)}

But

var now = new Date().setDate(0);
console.log(now)
// 1404142784241

Question:

What is difference between

var now = new Date();
now.setDate(0);

and

var now = new Date().setDate(0);

In the second example, you're looking at the return value of the .setDate() function, and not the date itself. The .setDate() function returns the timestamp value corresponding to the updated value of the object. It's like doing this:

var now = new Date();
now.setDate(0);
console.log(now.getTime());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM