2013-02-28 10 views
7

テスト期待としてUTCが動作しません:moment.js - 私はそれをノードのコンソールで

var moment = require('moment'); 

// create a new Date-Object 
var now = new Date(2013, 02, 28, 11, 11, 11); 

// create the native timestamp 
var native = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds()); 

// create the timestamp with moment 
var withMoment = moment.utc(now).valueOf() 
// it doesnt matter if i use moment(now).utc().valueOf() or moment().utc(now).valueOf() 

// native: 1364469071000 
// withMoment: 1364465471000 
native === withMoment // false!?!?! 

// this returns true!!! 
withMoment === now.getTime() 

なぜありえないネイティブwithMomentと同じタイムスタンプを?なぜwithMomentは現在の現地時間から計算されたタイムスタンプを返しますか?どのように私はそのmoment.utc()を達成することができますDate.UTC()と同じを返しますか?

答えて

11

コールmoment.utc()あなたがDate.UTCを呼び出しているのと同じ方法:

var withMoment = moment.utc([now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds()]).valueOf(); 

私はそれがローカルタイムゾーンでnowの生活を想定行いますmoment.utc(now)を呼び出すと思うし、それは違い、したがって、最初のUTCに変換します。

+1

既にそれを試して、それが動作することを見た。これは唯一の選択肢ですか?思考moment.jsは私にコードと時間を節約します;-( – hereandnow78

+0

'now'の代わりに' moment.utc() 'に' native'を渡すことができます、それはあまりにもうまくいくでしょう – robertklep

+0

ええ、 ;-) – hereandnow78

3

あなたがやっていることは本質的にこれです。

var now = new Date(2013, 02, 28, 11, 11, 11); 
var native = Date.UTC(2013, 02, 28, 11, 11, 11); 

console.log(now === utc); // false 
console.log(now - utc); // your offset from GMT in milliseconds 

nowは、現在のタイムゾーンで構成され、nativeがUTCに構成され、彼らはあなたのオフセットにより異なりますので。 11 AM PST!=午前11時GMT。

関連する問題