在momentjs中创建UTC时间会返回奇怪的结果

Creating UTC time in momentjs is returning weird results

本文关键字:返回 结果 时间 momentjs 创建 UTC      更新时间:2023-09-26

星期一晚上我要把我的听力搞砸了!有人能帮我理解下面的问题吗?我在浏览器01-09-2014上有以下字符串(这是本地时间),我想将其转换为UTC,以便将其保存回服务器。以下是我正在做的事情:

    var localDate = moment("01-09-2014", "DD-MM-YYYY");
    var utcDate = localDate.utc();
    console.log("Local Date " + localDate.toDate() + " UTC Date " + utcDate.toDate());

奇怪的是,最后一行输出:

Local Date Mon Sep 01 2014 00:00:00 GMT+0200 (Romance Daylight Time) UTC Date Mon Sep 01 2014 00:00:00 GMT+0200 (Romance Daylight Time) 

问题

  • 为什么UTC日期看起来与当地日期完全相同(鉴于我位于GMT+2区域,我预计当地时间会比UTC提前2小时)
  • 为什么UTC日期是GMT+0200?我预计UTC日期为GMT+000

你能帮我回答这两个问题吗?

Thoug我不确定。。。但我认为应该是:

var utcDate = localDate.utc().format()

参见:

http://momentjs.com/docs/#/parsing/utc/

更新

Fiddle:

http://jsfiddle.net/qhk9tnLr/2/

JS:

console.log("Local Date: " + moment("01-09-2014", "DD-MM-YYYY").toDate());
console.log("UTC Date: " + moment("01-09-2014", "DD-MM-YYYY").utc().format("ddd MMM DD YYYY HH:mm:ss zZZ"));

输出:

Local Date: Mon Sep 01 2014 00:00:00 GMT+0200
UTC Date: Sun Aug 31 2014 22:00:00 UTC+0000

结论:

toDate()将提供本地时间-使用utc().format() 获取UTC