简体   繁体   中英

JS Date cannot get the last day of month with 31 days

This month (March) has 31 days. I want to get the last day of the month and instead of get Wed Mar 31 2021 23:59:59 I get Fri Apr 30 2021 23:59:59 look:

let d = new Date()

d.setMonth( d.getMonth() + 1) // April
d.setDate(0) // should bring the 31 of March
d.setHours(23, 59, 59, 999)

console.log(d) // Fri Apr 30 2021 23:59:59 GMT+0300 (IDT)

Why does it happen on date with 31 days?

When tried on different months every month it worked as well, for example:

let d = new Date("2021-02-25") // notice that we point to February

d.setMonth( d.getMonth() + 1)
d.setDate(0)
d.setHours(23, 59, 59, 999)

console.log(d) // Sun Feb 28 2021 23:59:59 GMT+0200 (IST)

Notice that in the second example - which is working good, we get the last day of Feb and GMT+2 (IST) and not GMT+3 (IDT)

Also notice that if I declare it like that: let d = new Date('2021-03-25') it also works good (with specific date, instead of just new Date() )

It happens because April only has 30 days.

let d = new Date()

d.setMonth( d.getMonth() + 1) // Actually April 31st -> May 1st.

Got it!

I set +1 for the month while the current date is 31 and what will happen is that it will jump to 31 of April which doesn't exist and the default date will be 1 in May.

So prev date of 1 in May is 30 of April.

I should set the date to 1 before doing the increment of the month , look:

let d = new Date()

d.setDate(1) // this is the change - important!
d.setMonth( d.getMonth() + 1)
d.setDate(0)
d.setHours(23, 59, 59, 999)

console.log(d) // Wed Mar 31 2021 23:59:59

That way, it will start from 1 of March, inc to 1 of April, and go prev date to last day of March.

Even that it also works, weird:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1, 0, 0, 0, 0);
var lastDay = new Date(y, m + 1, 0, 23, 59, 59, 999)

console.log(lastDay)

Try this way:

d.setMonth(d.getMonth(), 0);

second argument 0 will result in the last day of the previous month

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