我正在尝试获取当月的第一个和最后一个日期和时间,我必须转换为 ISOString。 我在下面尝试过,但是当我转换 ISO 时,它减少了 1 天,并且在删除它之后到了正确的日期。
我必须用时间获得一个月的第一天和最后一天..
这是我想要的:
- 开始日期时间
2022-12-01T00:00:00.000Z
- 结束日期时间
2022-12-31T23:59:59.000Z
这是我的代码:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
console.log(firstDay.toISOString())
console.log(lastDay.toISOString())
console.log(firstDay)
console.log(lastDay)
结果:
// ISO string:
2022-11-30T18:30:00.000Z
2022-12-30T18:30:00.000Z
// without ISO string:
VM4876:4 Thu Dec 01 2022 00:00:00 GMT+0530 (India Standard Time)
VM4876:5 Sat Dec 31 2022 00:00:00 GMT+0530 (India Standard Time)
最佳答案
您可以使用 Date.UTC()帮助您在指定的 UTC 日期时间构建日期实例:
var firstDay = new Date(Date.UTC(y, m, 1));
var lastDay = new Date(Date.UTC(y, m + 1, 0, 23, 59, 59, 0));
您的日期实例现在将记录预期的 UTC 时间:
console.log(firstDay.toISOString())
console.log(lastDay.toISOString())
2022-12-01T00:00:00.000Z
2022-12-31T23:59:59.000Z
关于javascript - 如何在javascript中获取特定时间的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74794685/