【问题标题】:How can I get the current time using timezone offset using moment.js?如何使用 moment.js 使用时区偏移量获取当前时间?
【发布时间】:2020-07-02 07:17:44
【问题描述】:

我正在使用https://openweathermap.org/current api,我想获取目标城市的当前日期和时间,我从 api 获取时区(以秒为单位从 UTC 偏移)值,那么如何使用这个时区获取当前时间偏移值。

假设我从 api 收到了低于时区偏移值的值

const timezone = -14400

【问题讨论】:

  • 您的时区偏移量与 UTC 的时间差吗?您有实际结果与预期结果的示例吗?
  • 不要忘记时区!
  • 如何处理时区?我从 api 获取时区
  • 您可以添加示例 API 响应吗? moment.js(以及扩展名 luxon)都可以处理实例化具有指定区域的 DateTime 对象。 new Date(...) 正在创建一个 JS Date 对象,但其中包含您设备的时间和偏移量。
  • 你能分享timeunixvalue和它的实际日期值吗

标签: javascript reactjs momentjs unix-timestamp web-frontend


【解决方案1】:
const timezone = -14400 //needs to be converted in minutes 
const timezoneInMinutes = timezone / 60;
const currTime = moment().utcOffset(timezoneInMinutes).format("h:mm A");
// 10:10 PM

【讨论】:

    【解决方案2】:

    const dt = 1593674356; // unix timestamp in seconds
    const timezone = 3600; // zone in seconds
    
    // moment.unix - Unix Timestamp (seconds)
    const dateTime = moment.unix(dt).utc().add(timezone, 's');
    
    console.log(dateTime);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

    【讨论】:

    • 他真的需要一个 18kb 的库来完成一项简单的任务吗?
    • 您有更好的解决方案吗?
    • @AzeemAnsari 这个问题是直接问我还是 Lfaruki?
    • @DrewReese 那是给 Lfaruki 的,实际上你上面提到的代码对我不起作用,它在控制台中给了我本地时区(海湾标准时间)的对象,我不知道是否我遗漏了什么或犯了什么错误?
    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 2015-03-23
    • 2014-02-04
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多