获取每月的第一天和最后一天

时间:2020-10-21 15:39:20

标签: javascript node.js

此问题已得到here的回答,但是可能有些更改,因为它不再起作用。

function firstAndLast() {
  const startDate = new Date(2020, 8, 1);
  const endDate = new Date(2020, startDate.getMonth() + 1, 0)

  console.log('startDate', startDate) // <-- 2020-08-31T22:00:00.000Z
  console.log('endDate', endDate) // <-- 2020-09-29T22:00:00.000Z
}

firstAndLast();

文档说参数为new Date(YYYY, MM, DD, hh, mm, ss, ms)

我要输入年份2020,月份august(请注意,这不是节点而不是浏览器)和日期1。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

您必须考虑时区偏移量。 https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/getTimezoneOffset

function firstAndLast() {
  const offset = new Date().getTimezoneOffset() / 60

  const startDate = new Date(2020, 8, 1, 0-offset);
  const endDate = new Date(2020, startDate.getMonth() + 1, 0, 0-offset)

  console.log('startDate', startDate) // <-- 2020-08-31T22:00:00.000Z
  console.log('endDate', endDate) // <-- 2020-09-29T22:00:00.000Z
}

firstAndLast();