簡體   English   中英

日期顯示落后一天

[英]Dates display behind by a day

使用Moment.js時遇到一些奇怪的行為。 我在Date原型上附加了一些輔助類,這些輔助類顯然導致每個日期都落后一天。

Date.prototype.format = function(){
    return moment(this).format('MM/DD/YYYY')
}

var date = new Date('2008-05-13T00:00:00')

date.format() // => 05/12/2008, but should be 05/13/2008

我注意到了其他一些奇怪的事情:

date.getDate() // => yields 12, but should be 13

但是,如果我直接使用UTC字符串實例化Moment對象,那么它將起作用:

moment('2008-05-13T00:00:00').format('MM/DD/YY') // => 05/13/08

但是我正在處理普通日期對象,將每個日期修改為Moment對象並不是我的最愛。 我已經嘗試過修改format函數以從日期中提取UTC字符串,然后查看它是否正確顯示,但無濟於事。

date.toUTCString() // => Correctly yields "Tue, 13 May 2008 00:00:00 GMT"

moment(date.toUTCString()).format('MM/DD/YY') // => still 05/12/08

有什么想法嗎? 日期構造函數有問題嗎?

編輯:也輸出時間:

moment(date).format('MM/DD/YY hh:mm:ss') // => "05/12/08 08:00:00"

您必須告訴moment.js您以UTC顯示日期:

moment(this).utc().format('MM/DD/YYYY')

文檔中的更多信息: http : //momentjs.com/docs/#/parsing/utc/


但是,如果我直接使用UTC字符串實例化Moment對象,那么它將起作用:

 moment('2008-05-13T00:00:00').format('MM/DD/YY') // => 05/13/08` 

Moment.js 將參數解釋為本地時間

默認情況下,moment解析並以本地時間顯示。

new Date() (和Date.parse將值解釋為UTC時間

parse函數將生成的字符串解釋為日期和時間。 它返回一個數字,即與日期和時間相對應的UTC時間值。


我已經嘗試過修改格式函數以從日期中提取UTC字符串,然后查看它是否正確顯示,但無濟於事。

 date.toUTCString() // => Correctly yields "Tue, 13 May 2008 00:00:00 GMT" moment(date.toUTCString()).format('MM/DD/YY') // => still 05/12/08` 

date.toUTCString()產生的格式不是moment.js支持的任何格式 ,因此它回退到使用new Date() (它將字符串解釋為UTC時間,而不是本地時間)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM