当月的第一天和最后一天是错误的



我需要获取当前月份的第一天和最后一天。我使用核心JS new Date((方法创建了解决方案。

const date = new Date();
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
console.log(firstDay.toUTCString(), lastDay.toUTCString()); //Tue, 31 Mar 2020 18:30:00 GMT Wed, 29 Apr 2020 18:30:00 GMT

当我在浏览器控制台中尝试类似的操作时,它会按预期打印结果,即1st April 2020 and 30th April 2020,但在poster环境中测试它会给出错误的结果。

有人能帮忙解决这个困惑吗?

您的代码:

var d = new Date(),
e = new Date(d.getFullYear(), d.getMonth(), 1),
f = new Date(d.getFullYear(), d.getMonth() + 1, 0);

console.log(e.toUTCString() + "n" + f.toUTCString());

所以你得到了错误的结果,因为你想得到UTC字符串从本地日期开始,您需要将其设为UTC日期才能打印UTC字符串正确。

var d = new Date(),
e = new Date(Date.UTC(d.getFullYear(), d.getMonth(), 1)),
f = new Date(Date.UTC(d.getFullYear(), d.getMonth() + 1, 0));

console.log(e.toUTCString() + "n" + f.toUTCString());

最新更新