javascript-date

Convert nanoseconds timestamp to JavaScript Date()


I have a log with timestamps like, for example, 1686184163560519943. www.unixtimestamp.com says they're nanoseconds. I want to convert these to Date() and then to toLocaleTimeString().

Date() does not like this input and throws Invalid Date.

The prior people of the internet all seem to interested in getting to nanoseconds, not from them as I am.

Part of the problem, I think, is that when you convert it out of string form, what holds it is BigInt, and Date() doesn't want to take a BigInt.


Solution

  • The Date constructor accepts numbers as milliseconds, since your timestamp is in nanoseconds you can divide your number by 1000000 to do the conversion

    new Date(1686184163560519943 / 1000000);
    

    It returns the exact same date as unixtimestamp does when given your number in nanoseconds