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.
Did you ask for access to JSON? Need to receive the data and then use it. Forgot to add json tag. Several errors.
– Maury Developer
How could I do it the right way ? @Maurydeveloper
– Gabriel Silva
NOTE: I am having access to json, but I only put the code part where I am struggling...
– Gabriel Silva
Please pass full code. Few people will respond if you have so.
– Maury Developer
This may help you: https://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript
– Maury Developer