jstice4all
jstice4all

Reputation: 1948

How to parse date string from database without time shift?

I am getting 2016-07-13T00:00:00.000Z string from database and converting it to MM/DD/YYYY format with moment.js like this:

result = moment('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');

which prints 07/12/2016 but I was expecting 07/13/2016. Local Linux timezone is America/New_York. date command prints this Mon Jul 4 04:28:19 EDT 2016

Upvotes: 0

Views: 675

Answers (2)

Maggie Pint
Maggie Pint

Reputation: 2452

The date that you have is in UTC, as signified by the z at the end.

When you use the default moment constructor, moment(), it converts the time you pass it from the specified offset (in this case UTC) to the local time of the machine. This is why your date is changing. Because this is a UTC date, to keep it exactly the same you can use moment.utc():

moment.utc('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
"07/13/2016"

Alternately, parseZone would work as well:

moment.parseZone('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
"07/13/2016"

For more information about all of the constructor functions in moment, see the parsing guide or this blog post

Upvotes: 2

Lothereus
Lothereus

Reputation: 3919

You should use momentjs timezone : http://momentjs.com/timezone/

yourdate = moment.tz("2016-07-13T00:00:00.000Z", "America/New_York");
alert(yourdate.format('MM/DD/YYYY'));

This should give you the correct date in output.

Upvotes: 0

Related Questions