【问题标题】:Time conversion incorrect in momentjsmomentjs 中的时间转换不正确
【发布时间】:2019-03-13 23:57:26
【问题描述】:

我正在尝试使用 momentjs 在 typescript 中提取并进行一些时间计算,但是...

我得到不正确的时间值 11:51 PM

我应该到下午 4:51。

const m = moment('2019-03-13T16:51-07:00');
console.log(m.format('LT'));

【问题讨论】:

    标签: angular typescript momentjs


    【解决方案1】:

    这是意料之中的,因为您传递给 moment 函数的日期时间字符串输入中包含时区偏移量。 Moment 将根据时区偏移量将输入日期时间转换为本地日期时间。如果您想忽略(或者更确切地说保留)时区偏移量并获得确切的日期时间而不管浏览器时区如何,您可以使用 moment.parseZone 方法。

    Moment 的字符串解析函数如 moment(string) 和 moment.utc(string) 接受偏移信息(如果提供),但将生成的 Moment 对象转换为本地或 UTC 时间。相反,moment.parseZone() 解析字符串,但将生成的 Moment 对象保存在固定偏移时区中,并在字符串中提供偏移量。

     const m = moment.parseZone(ISODateTimeString);
     console.log(m.format('LT')); //"03/13/2019 4:51 PM" for en-US locale
    
    // or you can also use
    
     const m = moment(ISODateTimeString).utcOffset(ISODateTimeString);
    

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多