【问题标题】:How do I calculate the last day of any month in Javascript? [duplicate]如何在Javascript中计算任何一个月的最后一天? [复制]
【发布时间】: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() + 11 顺便说一句。
  • 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


【解决方案1】:

您可以使用值为 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

【讨论】:

  • 感谢您为我指明正确的方向。
猜你喜欢
  • 2010-09-16
  • 2010-09-18
  • 2012-03-12
  • 1970-01-01
  • 2016-03-23
  • 2011-05-03
  • 1970-01-01
  • 2011-06-07
  • 2015-02-06
相关资源
最近更新 更多