【问题标题】:convert string date and time to utc based on timezone using moment使用时刻根据时区将字符串日期和时间转换为 utc
【发布时间】:2020-10-07 09:20:22
【问题描述】:

我在 nodejs 服务器中使用 moment 将本地时间从前端转换为 utc。

我的时间格式是字符串格式的date = '10-07-2020 08:45 PM'。当我使用moment(date).format() 它的转换格式到这个2020-10-07 20:45:00+05:30 时区是基于服务器添加的,我有timezone = '+4:00' 这是我的本地时区。我想根据timezone 字段而不是基于服务器时区将我的日期字符串转换为UTC。我该怎么做?

我尝试了以下方法,但没有得到正确的解决方案

moment.utc(moment(date).utcOffset(timezone)).format('YYYY-MM-DD HH:mm:ss')

请大家推荐

【问题讨论】:

    标签: javascript node.js momentjs moment-timezone


    【解决方案1】:

    您可以使用moment-timezone 从字符串和特定时区创建日期。为此,您需要指定格式和相应的时区。像这样的:

    const date = moment.tz("10-07-2020 08:45 pm", "M-D-YYYY hh:mm a", "Europe/Samara");
    console.log(date.toISOString());
    <script src="https://momentjs.com/downloads/moment.min.js"></script>
    <script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>

    【讨论】:

    • @op:如果这解决了您的问题,请接受答案,谢谢。
    【解决方案2】:

    也许用intl DateTimeFormat代替moment?

    这里有一些可能性

    const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',  hour: 'numeric', minute: 'numeric', second: 'numeric', };
    
    const date = new Date('10-07-2020 08:45 PM')
    console.log(date)
    
    
    options.timeZone = 'Europe/Ulyanovsk';
    options.timeZoneName = 'short';
    console.log(new Intl.DateTimeFormat('en-US', options).format(date));

    【讨论】:

      猜你喜欢
      • 2012-11-08
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 2011-06-13
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多