【问题标题】:How to create a momentJS object with a specfic time and a specific timezone(other than the default local time zone)?如何创建具有特定时间和特定时区(默认本地时区除外)的时刻JS对象?
【发布时间】:2021-08-17 09:32:21
【问题描述】:

我将从前端收到一个字符串(带有时间和日期)。字符串格式是“2021-08-16T23:15:00.000Z”。我打算用输入字符串声明一个时刻对象,以及一个特定的时区(本地时区除外)。

    import moment from "moment";
    import "moment-timezone";



    // The input string I receive from the frontend.
    let strTime = "2021-08-16T23:15:00.000Z";

    console.log(strTime); //2021-08-16T23:15:00.000Z
    let time = moment.tz(strTime,  "YYYY-MM-DDTHH:mm:ss.SSSZ","America/Boise");

    console.log(time); // Moment<2021-08-16T17:15:00-06:00>, undesired value
    let UTCtime = moment.utc(time);
    console.log(UTCtime);

据我从this 问题中了解到的,console.log(time) 应该输出时间为 23:15:00 的时刻对象,但时区为“美国/博伊西”。

我打算time 拥有相同的时间,即“23:15:00.000”,时区为“美国/博伊西”。 因此,当我稍后将该时间转换为 UTC 时,我需要获得正确的值 w.r.t 时区“美国/博伊西”而不是我的本地时区。我该怎么做。

【问题讨论】:

    标签: momentjs moment-timezone


    【解决方案1】:

    我想出了一个解决办法。

        const momenttz = require("moment-timezone");
        const moment = require("moment");
        
        // The input string I receive from the frontend.
        let strTime = "2021-08-16T23:15:00.000Z";
        console.log(strTime); //2021-08-16T23:15:00.000Z
        
        let time = moment.utc(strTime);
        time.tz("America/Boise", true);
        console.log(time.tz());
        
        console.log(time); // Moment<2021-08-16T23:15:00-06:00>, desired value
        
        let UTCtime = moment.utc(time);
        console.log(UTCtime); // Moment<2021-08-17T05:15:00Z>
    

    在上面的代码中,console.log(time),time 的值为“23:15:00.000”,所需时区为“美国/博伊西”。这使您可以在以后将其转换为 UTC 时获得正确的值。

    这可以通过将可选的第二个参数传递给moment-timezone.tz 变体true 来实现,它只更改时区(及其相应的偏移量),而不影响时间值。

        time.tz(timezone, true);
    

    上面的答案代码中给出了使用它的示例。

    您可以在 Moment Timezone 文档中阅读更多相关信息 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多