2017-01-09 140 views
0

我一直在調試這個一會兒現在仍然沒有能夠弄明白。 _d時如何從在_i的時間不同具體請看。爲什麼?爲什麼在分配給變量時,moment.js會給出不同的結果?

var date = new Date('Fri, 06 Jan 2017 21:30:00 -0000') 
const momentDate = moment(date) 
console.log(`momentDate: `, momentDate); 
console.log(`moment(date): `, moment(date)); 

enter image description here

+1

一個創建瞬間的點.js是使用'Date'構造函數解析字符串是一個糟糕的想法(tm)。相反,使用'moment(string,format)','format'提供庫如何解析'string'。 –

+1

的可能的複製[momentjs內部對象是什麼 「\ _d」 與 「\ _i」](http://stackoverflow.com/questions/28126529/momentjs-internal-object-what-is-d-vs-i) –

+0

@MikeMcCaughan我真的開始了,但我得到了同樣的結果。 [CODE /輸出(http://imgur.com/a/BHxFk) –

回答

0

那麼是什麼原因導致的問題是我有被改寫值startOf('day')一個反應成分。如果您使用的時刻流入您的應用程序到時刻對象所有字符串日期轉換,如果遇到錯誤,一定要看看你的組件,而不是僅僅在爲API調用convertToMoment按摩功能。

更重要的是,直到那一刻3.0,所有時刻的對象是可變的,所以,如果你這樣做:

var a = moment() 
var b = a.startOf('day') 
console.log(a.format('LLL')) // January 22, 2017 12:00 AM 
console.log(b.format('LLL')) // January 22, 2017 12:00 AM 

解決這個問題的唯一方法可以是:

// use the cool `frozen-moment` package (which is basically a polyfill) 
var a = moment().freeze() 
var b = a.startOf('day') 
console.log(a.format('LLL')) // January 22, 2017 2:17 AM 
console.log(b.format('LLL')) // January 22, 2017 12:00 AM 

// or type `.clone()` everytime you want to use a cool function 
var a = moment() 
var b = a.clone().startOf('day') 
console.log(a.format('LLL')) // January 22, 2017 2:17 AM 
console.log(b.format('LLL')) // January 22, 2017 12:00 AM 
相關問題