Convert UTC date to local time in javascript (moment.js)
I am getting the following date as JSON data from ASP.NET webapi2 service.
{
creationDate: "2014-11-18T15:16:56.363"
... //other fields...
}
Dates in the system are stored as UTC dates, regardless of the time zone. The wrong time is used when data is returned and displayed on the screen, as the moment assumes the syntax date is local time and not UTC.
moment(text).tz('Africa/Johannesburg').fromNow();
Gives me the values โโof two hours in the past when they should really be current. How to parse / pass a date so that the moment knows it should add a timezone. In my case, GMT + 2 or SAST.
Adding the timezone (GMT) doesn't seem to help.
Date.parse('2017-04-15T09:09:48.9590011 UTC')
leads to NaN
source to share
You have at least two options:
-
Add
Z
to the end of the line:moment(creationDate + "Z")
-
Use
.utc
and then.local
:moment.utc(creationDate).local()
Here is an example using a date that is almost always in daylight saving time ("Daylight Saving Time"), so it even works for those of us in the UK (who are different in GMT, so it's hard to tell if we are getting UTC or local results:-)):
var creationDate = "2014-05-18T15:16:56.363";
console.log("String:", creationDate);
console.log("1:", moment(creationDate + "Z").toString());
console.log("2:", moment.utc(creationDate).local().toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
source to share
The problem is you are sending / receiving the date when the client and server will try to convert them to their timezone, the trick is to pass the date as a string. When you return or submit data, remove the "T"
{
creationDate: "2014-11-18 15:16:56.363"
... //other fields...
}
OR
data.creationDate.replace('T', ' ')
Therefore, when the customer receives the data, he will not change or convert the date. then you can use
new Date(moment(data.creationDate.replace('T', ' ')))
This will return what you sent from the server
source to share