1

I have seen a variety of threads that are adjacent to this topic. However, my google fu has failed me so far.

I have a value on my server that is a date represented as a string. I am certain it is the milliseconds since the UTC epoch.

I will write it like this for stackOverflow:

const k = '1638400203941'
Date.parse(k); // NaN
const a = parseInt(k, 10);
Date.parse(a); // NaN

// ah ha! but what about...
Date.parse(Date.now() - a); // nope, NaN

I am sure this has been done a thousand times before but how do I do this?

To clarify, the goal is to parse my server's output, k = 1638400203941 into a date. YYYY-MM-DD or MM-DD-YYYY is ok.

edit: Somehow I didn't think to try the given solution. It was giving me Invalid date for some reason, guessing that I was passing in the string version instead of int. My mistake guys.

plutownium
  • 1,220
  • 2
  • 9
  • 23

1 Answers1

0

Just use new Date with you time in numerical format. I used + to convert the string to number.

const k = '1638400203941'
console.log(new Date(+k));
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • 1
    For a more readable solution, you can write `new Date(parseInt('1638400203941'))`, so future programmers will know what's going on at a glance. – samuei Dec 28 '21 at 08:05
  • I prefer to use `+` over `parseInt` for direct numerical conversion. For better understanding I have mentioned the logic in the answer description. – Nitheesh Dec 28 '21 at 08:35