Epoch in JavaScript
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in JavaScript.
To run the program:
In JavaScript, we use the Date
object to work with dates and times. The Date.now()
method returns the number of milliseconds since the Unix epoch.
Unlike some other languages, JavaScript doesn’t have built-in methods to get the time in seconds or nanoseconds since the epoch. However, we can easily calculate these:
- For seconds, we divide the millisecond timestamp by 1000 and round down.
- For nanoseconds, we multiply the millisecond timestamp by 1,000,000. Note that JavaScript doesn’t actually have nanosecond precision, so this is just an approximation.
To convert a timestamp back into a Date
object, we can use the Date
constructor with the millisecond timestamp.
Next, we’ll look at another time-related task: date parsing and formatting in JavaScript.