【发布时间】:2021-09-09 08:48:07
【问题描述】:
如何在 Javascript 中正确计算每个月的最后一天?
按照我在代码中的思考过程来计算 2021 年 7 月的最后一天。
let tzoffset = new Date().getTimezoneOffset() * 60000;
//### Calculates the TIME at which today started
let todayStartedAt = new Date(new Date().setHours(0,0,0,0) - tzoffset );
console.log('Today Started At: ' +todayStartedAt.toISOString());
//### Calculates the first day/date TWO months ago
let twoMonthsAgo = todayStartedAt;
twoMonthsAgo.setMonth(todayStartedAt.getMonth() - 2);
twoMonthsAgo.setDate(twoMonthsAgo.getDate() - twoMonthsAgo.getDate() + 1 );
console.log('The first day 2 Months Ago was on: ' +twoMonthsAgo.toISOString());
var month = twoMonthsAgo.getMonth(); // July = 6
let year = twoMonthsAgo.getFullYear(); // 2021
//### Calculates the LAST day/date TWO months ago
var theLastDayTwoMonthsAgo = new Date(twoMonthsAgo.getFullYear(), twoMonthsAgo.getMonth() +1, 0);
console.log("The Last Day Two Months Ago was: " +theLastDayTwoMonthsAgo.toISOString() );
上面的代码产生:
Today Started At: 2021-09-09T00:00:00.000Z
The first day 2 Months Ago was on: 2021-07-01T00:00:00.000Z
The Last Day Two Months Ago was: 2021-07-30T21:00:00.000Z
请注意,The Last Day Two Months Ago 的结果是错误的,因为 7 月的最后一天 NOT 在 7 月 30 日结束,而不是在 7 月 31 日结束。
其次,请注意日期的时间部分是:T21:00:00.000Z 如何将其更改为 T23:59:59.000Z
【问题讨论】:
-
twoMonthsAgo.getDate() - twoMonthsAgo.getDate() + 1是1顺便说一句。 -
new Date(new Date().setHours(0,0,0,0) - tzoffset );如果在更改当天的夏令时更改之后调用,将返回不正确的结果。无论如何,new Date(new Date().setUTCHours(0,0,0,0))可以用更少的代码完成这项工作(尽管创建两个 Date 对象而不是一个可能性能不佳,let d = new Date(); d.setUTCHours(0,0,0,0)的代码更少)。 :-)
标签: javascript date