Nathan Kamenar
Nathan Kamenar

Reputation: 884

Converting Date to JS Date Object

I have a date in a weird format and I am not sure how to turn it into a JS Date Object. I am sure libraries like moment.js have utilities for this but I don't really want to load an entire library just for this conversion. Here is the data:

/Date(1472586116588-0400)/

EDIT: I have updated the back end code to use a string in the JSON instead of a C# Date time and then I convert the DateTime as follows:

Date.ToString("s");

This is giving me this string: 2016-09-02T10:13:12

So now my problem is if I do var date = new Date("2016-09-02T10:13:12"); javascript gives back:

Fri Sep 02 2016 06:13:12 GMT-0400 (EDT)

But it should give me:

Fri Sep 02 2016 10:13:12 GMT-0400 (EDT)

It appears the time zone conversion is being like doubled or something? Anyone know how to fix this?

Upvotes: 0

Views: 1373

Answers (2)

Nathan Kamenar
Nathan Kamenar

Reputation: 884

Fixed by changing backend data to string in ISO 8601 formate instead of C# DateTime as follows:

date.ToString("o");

This can then simply be turned into a javascript date using new Date({string here});

Credit to James Thorpe for suggesting fixing JSON data on backend rather than hacking it to fit on the front end.

Upvotes: 0

user663031
user663031

Reputation:

I am assuming this is milliseconds since the epoch, with an hhmm offset, so I would do:

var input = "/Date(1472586116588-0400)/";
var [match, msec, offset] = input.match(/\((\d+)([+-]\d+)\)/);
var offsetHours = Math.floor(offset / 100);
var offsetMinutes = offset - offsetHours * 100;
var date = new Date(msec - offsetHours * 60 * 60 * 1000 - offsetMinutes * 60 * 1000);

console.log(date);

Upvotes: 0

Related Questions