从Moment.js中的UTC日期字符串创建本地日期

时间:2015-03-05 23:01:02

标签: javascript date timezone momentjs utc

给定UTC日期字符串(格式为:YYYYMMDDHHmmss)我想使用Moment.js创建一个带有本地时区的日期。我尝试过以下方法:

var utcDateStr = '20140101120000';
var localDate = moment.utc(utcDateStr, 'YYYYMMDDHHmmss');

//actual: true
//desired: false
console.log(localDate._isUTC)

//actual: "Wed Jan 01 2014 12:00:00 GMT+0000"
//desired: "Wed Jan 01 2014 07:00:00 GMT-0500"
console.log(localDate.toString())

当我拨打toString()时,如何创建默认情况下在本地时区格式化的日期?

2 个答案:

答案 0 :(得分:2)

只需使用版本1.5.0中添加的.local()功能。

var localDate = moment.utc(utcDateStr, 'YYYYMMDDHHmmss').local();

答案 1 :(得分:0)

// UTC time
var utcDateStr = '20140101120000';

// First way
var offset = moment().utcOffset();
var localtime = moment.utc(utcDateStr,'YYYYMMDDHHmmss').utcOffset(offset);

// Another way
var anotherLocaltime= moment.utc(utcDateStr, 'YYYYMMDDHHmmss').local();

这两种方式都很好......请参阅JsFiddle