【问题标题】:How to add timestamp in local time in momentjs如何在momentjs中添加当地时间的时间戳
【发布时间】:2017-03-17 12:53:11
【问题描述】:

我正在使用 moment.js 并且在编号/时间戳中具有 datetime。我想将其转换为我的本地时间戳,即GMT+5:30。这是jsfiddle链接。

代码:-

console.log(moment(1489689000000).add(52200000).toDate())

  //output: Fri Mar 17 2017 14:30:00 GMT+0530 (IST)
 //expected output : Fri Mar 17 2017 20:00:00 GMT+0530 (IST)

【问题讨论】:

  • moment.js 无论如何都会拉本地时间,根据文档,尝试 moment().format('MMMM Do YYYY, h:mm:ss a');

标签: javascript node.js momentjs


【解决方案1】:

时刻

如果你想在你的问题中使用普通的moment

如果您希望将日期解析为 UTC,可以尝试使用 moment.utc()

console.log(moment.utc(1489689000000).add(52200000).local().toDate());

或:

console.log(moment(moment.utc(1489689000000).add(52200000).local()));

这实际上可能无法满足您的需求 - 取决于您的系统配置。

时刻时区

如果您对时区很认真,那么您应该使用moment-timezone

var moment = require('moment-timezone');
var zone = moment.tz.guess();
console.log(moment.utc(1489689000000).add(52200000).tz(zone).format());

见:

【讨论】:

  • 我认为您的代码也给出了 Fri Mar 17 2017 14:30:00 GMT+0530 (IST) 但预期的输出被提到为 Fri Mar 17 20:00:00 GMT+0530 (IST) )
  • 不希望输出..!实际上,当我从下拉列表中选择“20:00”时,数字 52200000 来自前端 bs-datepicker
  • @user7104874 查看我的更新答案 - 最后一个示例和链接。
【解决方案2】:

这里有一些其他的方法来实现这一点。根据您的GMT +5.30 时区,您只需将小时转换为毫秒。

console.log(moment(1489689000000).add(52200000+ 19800000).toDate());

 // here 5.5 hours =  19800000 miliseconds
// add  + 19800000 due GMT +5.30

【讨论】:

    【解决方案3】:

    非常适合您当地的时区 - 时刻对象将为您提供完美的日期

    moment().toDate() // Fri Mar 17 2017 20:18:53 GMT+0530 (IST)
    

    但是如果你想要不同的时区,完美的方法是转换using moment timezone

    moment().tz(timezone)toDate()
    eg. moment().tz('Asia/calcutta').toDate() // Fri Mar 17 2017 20:20:49 GMT+0530 (IST)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2018-08-16
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      相关资源
      最近更新 更多