使用Moment.js时startOf与endOf结果异常的技术问询
问题解答
1. 代码是否受本地时区(KST)影响?
当前代码不受KST时区影响。原因在于:
- 你的Node.js环境时区被配置为UTC(从
Intl.DateTimeFormat().resolvedOptions().timeZone返回结果可确认) - Moment.js默认会使用运行环境的时区进行时间计算,因此
startOf('day')和endOf('day')都是基于UTC时区计算的,最终输出的Date对象也以UTC时区的ISO格式展示,和服务器的KST本地时区无关。
2. 能否将开始时间设为15:00:00?
可以实现,需根据需求明确时区(是UTC的15点还是KST的15点),以下是两种场景的实现方式:
场景1:设置当前小时的起始时间(比如当前KST时间15:59,就设为15:00)
需要先切换到KST时区计算,这需要用到moment-timezone插件(Moment.js核心库不支持时区切换):
const moment = require('moment-timezone'); // 切换到KST时区(Asia/Seoul) const kstNow = moment().tz('Asia/Seoul'); // 获取当前小时的起始时间(15:00:00 KST) const beginDate = kstNow.startOf('hour').toDate(); console.log(beginDate); // 对应UTC时间为06:00:00的ISO字符串
场景2:设置当天固定的15:00:00作为开始时间
同样基于KST时区设置固定小时:
const moment = require('moment-timezone'); const kstNow = moment().tz('Asia/Seoul'); // 将时间设置为当天15:00:00 const beginDate = kstNow.set({ hour: 15, minute: 0, second: 0, millisecond: 0 }).toDate(); console.log(beginDate);
如果不需要KST时区,直接基于UTC时区设置15:00,无需时区插件:
const beginDate = moment().set({ hour: 15, minute: 0, second: 0, millisecond: 0 }).toDate(); console.log(beginDate); // 输出UTC时间15:00:00的ISO字符串
内容的提问来源于stack exchange,提问作者Minwoo Kim
相关产品推荐
相关产品推荐

