You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript/Moment.js中将本地日期转为UTC的00:00:00和23:59:59?

解决方案

你可以使用Moment.js的startOf()和endOf()方法来精准定位UTC日期的起始和结束时刻,修改后的代码如下:

// 获取昨日UTC的起始时间(00:00:00Z)
$scope.fromDate = moment.utc().subtract(1, 'days').startOf('day').format();

// 获取今日UTC的结束时间(23:59:59Z)
$scope.toDate = moment.utc().endOf('day').format();

代码说明

  • moment.utc():直接创建UTC时区的moment对象,避免本地时间转换带来的偏差
  • .subtract(1, 'days'):将日期往前推1天,定位到昨日
  • .startOf('day'):将时间重置为当天的起始时刻(00:00:00)
  • .endOf('day'):将时间设置为当天的最后一刻(23:59:59)
  • .format():默认输出ISO 8601格式的UTC时间(带Z后缀)

执行后就能得到你需要的格式:

  • StartDate: 2023-02-19T00:00:00Z
  • EndDate: 2023-02-20T23:59:59Z

内容的提问来源于stack exchange,提问作者Ranjan Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 12:01:00