moment.utc(date).local()仍然给出了utc时间。

时间:2017-06-30 23:00:27

标签: javascript datetime momentjs

我以2017-06-28 23:24:17.1-07的格式从数据库中获取时间戳,我尝试使用片刻将其转换为本地时间,但我还是回到UTC时间。

这是我插入控制台的模拟版本:

var now = new Date(); // Fri Jun 30 2017 15:45:30 GMT-0700 (PDT)

// simulate date received from server
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); // Fri Jun 30 2017 22:45:41 GMT-0700 (PDT);

var local = moment.utc(now_utc).local().format('LLL') // "June 30, 2017 10:45 PM"

^ should be ~3:45pm.

如您所见,local的输出与now_utc的输入相同。

2 个答案:

答案 0 :(得分:1)

  

我从self.tableView.delegate = self格式的数据库中获取时间戳,我正试图将其转换为当地时间...

直接从数据库获取这是一种相当不寻常的字符串格式,但如果确实是你拥有的字符串,那么:

2017-06-28 23:24:17.1-07

根本不需要使用// parse the input string var m = moment("2017-06-28 23:24:17.1-07", "YYYY-MM-DD HH:mm:ss.SZ"); // format the output string var s = m.format("LLL"); 对象,也不需要调用Date,因为本地模式是默认设置,并且您提供了偏移量。

答案 1 :(得分:0)

我有同样的问题。使用时刻 - 时区解决了我的问题,虽然我不明白为什么.local()没有工作。

尝试按如下方式修改本地变量:

var local = moment.utc(now_utc).tz(时区).format(' LLL')

您可以找到所需的时区值enter image description here

P.S。别忘了安装moment-timezone软件包。