2

receiving string of date that looks like this "/Date(1633421520000)/",

with moment I could just use it as moment("/Date(1633421520000)/") whats the equivalent for date-fns ?

for example differenceInMilliseconds how would i use it with received argument as this string "/Date(1633421520000)/"

not sure how to create my date object from this string so ill be able to use date-fns functions.

greW
  • 1,248
  • 3
  • 24
  • 49

1 Answers1

1

You need to extract the number (which looks like milliseconds since unix epoch) from the string:

"/Date(1634717139973)/".match(/\d+/)[0]

Then use Date constructor like so:

var date = new Date(Number("/Date(1634717139973)/".match(/\d+/)[0]));
date.toISOString(); // 2021-10-20T08:05:39.973Z
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • 1
    moment works just fine like this `moment("/Date(1633421520000)/")`, the question whats the equivalent to use this format with date-fns ? – greW Oct 20 '21 at 08:43
  • 1
    `new Date(Number("1634717139973"))` will give you a JavaScript date object, if that is what you're after. – Salman A Oct 20 '21 at 08:45
  • The problem with using *match* is that if there is no match, you'll get an error whereas if you use something like *replace*, e.g. `new Date(Number("/Date(1634717139973)/".replace(/\D/g,''))).toISOString()` which always returns a Date object and won't throw errors if given say "/Date" (i.e. there are no digits). You just have to test if the returned Date is valid or not (e.g. `if (isNaN(dateObj)) ...`). :-) – RobG Oct 20 '21 at 12:34