0

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?

Nathan Kamenar
  • 824
  • 7
  • 30
  • MDN Docs [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) – Jecoms Sep 02 '16 at 13:43
  • Is that supposed to be Unix timestamp? – Bwaxxlo Sep 02 '16 at 13:44
  • var dateObject=new Date(1472586116588-0400); is this you want? – Ravin Singh D Sep 02 '16 at 13:45
  • It would help if you describe what format that data is actually in. – DBS Sep 02 '16 at 13:45
  • 1
    A better fix here would be to go to the source of your string (this looks like a typical JSON serialised output from .NET for example), and update it to emit a date in the [format as per the spec](http://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format), so it is [easily parseable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) in any browser. – James Thorpe Sep 02 '16 at 13:46
  • Its TIMESTAMP ??? check http://stackoverflow.com/questions/19485353/function-to-convert-timestamp-to-human-date-in-javascript – KingRider Sep 02 '16 at 13:46
  • Updated with new changes. Decided to go route recommended by James Thorpe – Nathan Kamenar Sep 02 '16 at 14:36

2 Answers2

0

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);
0

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.

Nathan Kamenar
  • 824
  • 7
  • 30