0

I'm attempting to convert a Date that is returning from the database as /Date(1570474808430)/. I'd like to convert it as a standard date time result such as it's appearing in the database as : 2020-08-04 11:08:22.630. Is this something that is possible? I'm not entirely sure why it appears as date time in the database but is returning as /Date(1570474808430)/ on the front end.

I've attempted to approach this with the following code:

let oldDate = /Date(1570474808430)/

let updatedDate = new Date(oldDate);

console.log(updatedDate)

My expected result is to convert /Date(1570474808430)/ to a date time: 2020-08-04 11:08:22.630

maimok
  • 333
  • 1
  • 3
  • 12
  • What are those slashes? – Dominik Matis Sep 02 '20 at 19:45
  • 1
    Do you realise that slashes are delimiters for a RegExp literal? What you get from the database is probably a string, so an example string should have string literal delimiters (quotes) – trincot Sep 02 '20 at 19:50
  • What is the number? If that number should produce the date you say, it certainly is not a unix epoch number... – trincot Sep 02 '20 at 19:53

1 Answers1

3

Your snippet, perhaps unknown to you, actually tries to pass a regular expression literal to the Date constructor. What comes back from your API is actually a string - of the form /Date(xxx)/ where xxx appears to be a Unix timestamp. In order to translate this to a Javascript date object, we need to parse the timestamp out of that - assuming the data always has this format - and ironically, the simplest way to do that is probably a regular expression:

const oldDate = "/Date(1570474808430)/";

const timeStamp = Number(oldDate.match(/\/Date\((\d+)\)\//)[1]);

const updatedDate = new Date(timeStamp);

console.log(updatedDate)

This works if you can guarantee your data will be in this form - but frankly it is not good code, and will certainly lead to problems if your data isn't always in this format. The best thing you could do, if it's possible, would be to update your data so that it holds a sensible date-string in a standard format. Or failing that, at least a number representing the Unix timestamp, without the /Date(...)/ cruft.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34