如何在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
相关产品推荐
相关产品推荐

