如何在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
的结果是错误的,因为NOT
在7月的最后一天结束于7月30日,而不是7月31日。其次,请注意日期的时间部分为:T21:00:00.000Z
我如何将其更改为读取T23:59:59.000Z
可以使用值为0(0)的setDate()
的例子:
let august=new Date(2021,7,1); //Take first day of august, to find last day of July
august.setDate(0); // This is now the last day of July
例如,dayValue参数为0,则设置日期为上个月的最后一天。
从这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate