【问题标题】:Getting datetime as a string in current timezone在当前时区中将日期时间作为字符串获取
【发布时间】:2020-04-28 10:33:25
【问题描述】:

在 MySQL 数据库中:'2020-04-19 22:00:00'(UTC)。这也是我的端点返回的内容,因为我设置了连接选项dataStrings:true

在客户端,我获取date后:

const timezone = moment.tz.guess();

const convertedDate = moment(date)
   .tz(timezone)
   .format();

convertedDate 等于 "2020-04-19T22:00:00+02:00"(我在 UTC+2 区域)。

我想改为“2020-04-20T00:00:00”格式。我该怎么做?

【问题讨论】:

    标签: timezone momentjs moment-timezone


    【解决方案1】:

    看起来moment(date) 认为您传入的date 值是当地时间,而不是UTC。因此,您的时区转换为本地时间不会改变任何事情。你可以告诉moment这是UTC,像这样:

    const timezone = moment.tz.guess();
    
    const convertedDate = moment.utc(date)
       .tz(timezone)
       .format();
    

    【讨论】:

      【解决方案2】:

      为此,您不需要时刻时区。 Moment 本身可以在解析时使用utc 函数,在格式化之前使用local 函数转换为用户的本地时区。

      moment.utc('2020-04-19 22:00:00').local().format()
      
      //=> "2020-04-20T00:00:00+02:00"
      

      此外,Moment 团队建议仅将 Moment 用于现有项目。对于新开发,我们建议改用Luxon

      luxon.DateTime.fromSQL('2020-04-19 22:00:00', {zone: 'utc'}).toLocal().toISO()
      
      //=> "2020-04-20T00:00:00.000+02:00"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-09
        • 2014-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-03
        • 2016-05-13
        相关资源
        最近更新 更多