如何在JavaScript中获取带指定时间的当月首尾日期并转为ISOString
问题:获取当月首尾日期的ISO格式时间偏差问题
我想要获取当前月份的第一天(00:00:00)和最后一天(23:59:59)的日期时间,并转换为ISOString格式。但用现有代码转成ISOString时日期会提前一天,直接打印日期对象却显示正确。期望格式:
- 起始时间:
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)
问题原因
toISOString()方法会将日期转换为UTC时区的字符串,而你的本地时区是GMT+0530(印度标准时间),本地时间的00:00:00转换为UTC时就是前一天的18:30:00(00:00 - 5小时30分 = 18:30)。直接打印日期对象时,显示的是本地时区的时间,所以看起来正确。
解决方法
方法1:构造UTC时区的首尾时间
如果需要的是UTC时区的当月首尾时间,直接用Date.UTC()构造:
const now = new Date(); // UTC当月第一天00:00:00 const firstDayUTC = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)); // UTC当月最后一天23:59:59 const lastDayUTC = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0, 23, 59, 59)); console.log(firstDayUTC.toISOString()); // 输出类似2022-12-01T00:00:00.000Z console.log(lastDayUTC.toISOString()); // 输出类似2022-12-31T23:59:59.000Z
方法2:手动拼接目标格式字符串
如果需要固定日期格式(不涉及时区转换),可以直接拼接字符串:
const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); // 起始时间字符串 const firstDayStr = `${year}-${month}-01T00:00:00.000Z`; // 获取当月最后一天的日期 const lastDate = new Date(year, now.getMonth() + 1, 0).getDate(); // 结束时间字符串 const lastDayStr = `${year}-${month}-${String(lastDate).padStart(2, '0')}T23:59:59.000Z`; console.log(firstDayStr); console.log(lastDayStr);
内容的提问来源于stack exchange,提问作者abhigyan kr
相关产品推荐
相关产品推荐

