【问题标题】:How to get date and time using moment for a given timezone offset如何使用给定时区偏移量的时刻获取日期和时间
【发布时间】:2021-10-03 03:51:00
【问题描述】:
{
    "time": 1627375726.8367202,
    "tzoffset": -25200,
    "ok": 1
}

使用上面的 JSON 我需要获取日期、时间和时区。我尝试了很多方法,但都没有成功。有没有办法获取日期、时间和时区。我正在使用 JavaScript。

谢谢,

【问题讨论】:

标签: javascript momentjs moment-timezone


【解决方案1】:

看看Documentation

这里有一个小例子

moment.parseZone("2013-01-01T00:00:00-13:00").utcOffset(); // -780 ("-13:00" in total minutes)

【讨论】:

    【解决方案2】:

    我们可以使用moment.utcOffset 函数使用您指定的unix 时间和偏移量来获取当前日期和时间。我们必须将您的 tzoffset 除以 60,因为它(大概)以秒为单位,而 moment 预计为分钟。

    通常不可能获得唯一的时区值,因为您的 tzoffset 将由多个区域共享,我们能做的最好的就是获得这些列表:

    const input = {
        "time": 1627375726.8367202,
        "tzoffset": -25200,
        "ok": 1
    };
    
    console.log("UTC time:", moment.unix(input.time).utc().format('YYYY-MM-DD HH:mm'))
    console.log("Time in Timezone:", moment.unix(input.time).utcOffset(input.tzoffset / 60).format('YYYY-MM-DD HH:mm'))
    console.log("Time in Timezone (with offset):", moment.unix(input.time).utcOffset(input.tzoffset / 60).format())
    console.log("Possible timezones:", getPossibleTimezones(input.time, input.tzoffset))
    
    function getPossibleTimezones(time, tzoffset) {
        return moment.tz.names().filter(zone => moment.tz(moment.unix(time), zone).utcOffset() === input.tzoffset / 60);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script>
    <script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script> 

    我也会考虑使用luxon,因为现在正在维护中。

    我们可以使用 FixedOffsetZone 来获取该区域的本地时间:

    const input = {
        "time": 1627375726.8367202,
        "tzoffset": -25200,
        "ok": 1
    };
    
    let { DateTime, FixedOffsetZone } = luxon;
    
    let zone = new FixedOffsetZone(input.tzoffset / 60)
    
    console.log("UTC time:", DateTime.fromSeconds(input.time, { zone: 'UTC' }).toISO())
    console.log("Time in timezone:", DateTime.fromSeconds(input.time,  { zone: zone }).toISO())
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.0.1/luxon.min.js" integrity="sha512-bI2nHaBnCCpELzO7o0RB58ULEQuWW9HRXP/qyxg/u6WakLJb6wz0nVR9dy0bdKKGo0qOBa3s8v9FGv54Mbp3aA==" crossorigin="anonymous" referrerpolicy="no-referrer"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 1970-01-01
      • 2013-01-14
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      相关资源
      最近更新 更多