ncksllvn
ncksllvn

Reputation: 5769

Dates display behind by a day

I'm encountering some weird behavior while using Moment.js. I have some helper classes attached to the Date prototype, which are apparently are causing each date to display behind by a day.

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

A couple of other weird things I've noticed:

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

But, if I instantiated the Moment object directly with the UTC string, then it works:

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

But I'm dealing with plain date objects, and modifying every date to a Moment object isn't my favorite idea. I have already tried modifying the format function to extract the UTC string from the date and see if it displays correctly then, but to no avail.

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

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

Any ideas what's happening here? Is there a problem with the date constructor?

EDIT: Outputting the time as well:

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

Upvotes: 1

Views: 128

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

You have to tell moment.js that you to display the date in UTC:

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

More in the documentation: http://momentjs.com/docs/#/parsing/utc/


But, if I instantiated the Moment object directly with the UTC string, then it works:

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

Moment.js interprets the argument as local time:

By default, moment parses and displays in local time.

Whereas new Date() (and Date.parse) interpret the value as UTC time:

The parse function [...] interprets the resulting String as a date and time; it returns a Number, the UTC time value corresponding to the date and time.


I have already tried modifying the format function to extract the UTC string from the date and see if it displays correctly then, but to no avail.

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

The format that date.toUTCString() yields is not in any of the formats that moment.js supports, so it falls back to using new Date() (which interprets the string as UTC time, not local time).

Upvotes: 1

Related Questions