2013-07-01 53 views
4

林試圖發送一個API一個asp.net UTC時間戳是這樣的:Momentjs UTC時間是古怪

d = new Date() 
test = moment(d).utc().valueOf() 
test2 = moment(d).utc().format("ZZ") 
utc_asp = "/Date("+test+test2+")/" 
console.log utc_asp 
>> /Date(1372670700799+0000)/ 

但服務器獲取的時間是一樣的本地時間?

或者這樣:

console.log moment(d) 
console.log moment(d).utc() 

D {_i: Mon Jul 01 2013 11:26:10 GMT+0200 (SAST), _f: undefined, _l: undefined, _isUTC: false, _d: Mon Jul 01 2013 11:26:10 GMT+0200 (SAST)…} 
index.js:39 
D {_i: Mon Jul 01 2013 11:26:10 GMT+0200 (SAST), _f: undefined, _l: undefined, _isUTC: true, _d: Mon Jul 01 2013 11:26:10 GMT+0200 (SAST)…} 

這樣做:

console.log moment(now).utc().hour() 
>> 9 - This is correct! Its 11 - 2, but how come the above 

我這樣做是不正確的?

+0

我有類似的問題。無法獲取本地時間戳,並將其轉換爲UTC轉換爲javascript日期格式。你能解決嗎? – Cmag

回答

0

我不確定,但請嘗試檢查您的asp.net日期時間是否使用localtime,utc或未指定的反序列化。

2

要從當前日期創建一個片刻,只需使用moment()而不帶任何參數。

var m = moment(); // returns a moment representing "now" 

如果再要它與MS專有/Date()/格式格式,您可以使用:

m.format("/[Date](XSSS)/") 

這會給你這樣的值,/Date(1372728650261)/適於傳遞給.Net和最終會給你一個DateTime對象,其中.KindUtc

如果你想與膠印的擴展格式,您可以使用此:

m.format("/[Date](XSSSZZ)/") 

,它會給你回一個值,如/Date(1372728650261-0700)/。這符合.Net中DataContractJsonSerializer類的要求。請參閱these docs中標題爲「DateTime連線格式」的部分。

但是,我強烈建議你不要使用後一種格式。它只被DataContractJsonSerializer識別,文檔明確指出,無論您提供的偏移量將被忽略 - 而是使用服務器自己的偏移量。這很愚蠢,但它就是這樣。如果您使用的是JavaScriptSerializer類,則偏移量也會被忽略,但它的行爲與DCJS不同(保持UTC而不是本地)。

對於這個問題,我會建議完全放棄這種奇怪的格式。改用ISO8601標準(例如,2013-07-01T18:38:29-07:00)。這很容易用momentjs完成,並且是默認格式。

moment().format() // it's the default, no need to specify anything. 

在服務器端,使用JSON.Net,這也默認使用這種格式。如果您真的關心偏移量,請在服務器上使用DateTimeOffset類型,而不要使用DateTime類型。

+0

我正在找'moment().format()'。謝謝 –