Unixtimestamp for Date Javascript

Asked

Viewed 93 times

3

I am receiving a JSON in which the date is being returned in this way:

    /Date(1563568740000+0200)/

I believe it is Unixtimestamp, but I can not convert it to format Date javascript.

I’ve tried to do it that way:

    console.log(new Date(Data*1000));

But in the browser console it shows me "invalid date".

What am I doing wrong?

  • Did you ask for access to JSON? Need to receive the data and then use it. Forgot to add json tag. Several errors.

  • How could I do it the right way ? @Maurydeveloper

  • NOTE: I am having access to json, but I only put the code part where I am struggling...

  • Please pass full code. Few people will respond if you have so.

  • This may help you: https://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript

1 answer

5


If this came from a JSON, it’s probably a string containing the text "/Date(1563568740000+0200)/" (since the JSON does not define a specific type for dates).

One way to solve it is to extract the content that matters (in this case, the giant number, which is a timestamp) and use it in constructor Date:

let s = "/Date(1563568740000+0200)/";
let match = /\/Date\((\d+).*\)\//.exec(s);
let d = new Date(parseInt(match[1]));
console.log(d);

The regex uses \d+ (one or more digits) in parentheses as this forms a catch group, that I can recover after with match[1] (i use 1 because it is the first capture group of regex).

Some characters (such as bar and parentheses) should be escaped with \, because they have special meaning in regex, but in this case I want them to be interpreted as the characters themselves, so that they match the bars and parentheses of the string.

Then use parseInt to convert it into number and step to the constructor of Date.

As explained above here, one Date encapsulates only the value of the timestamp, so the rest (offset +0200) is irrelevant to its creation. That’s why I use .* (zero or more characters), as it only serves for regex to go to the next bar at the end of the string.

  • 1

    Dude, you really helped me @hkotsubo

  • You forgot to multiply by 1000. let d = new Date(Math.trunc(+match[1]) * 1000);

  • @Maurydeveloper This amount is already in milliseconds and does not need it. If I multiply 1563568740000 by 1000, the resulting date will be in year 51517

  • 1

    Sorry then. I vote for you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.