✒️
Start your developer blog today!
✉️
Questions?
Email me

How to Get the Epoch from a Date in JavaScript

Feb 26, 2021 1 min read

Suppose we have a date 04-20-2021 (April 20, 2021), and we want to get the epoch for that specific date.

We can obtain the epoch using the built-in Date object.

new Date('04-20-2021').getTime() / 1000 // 1618894800

If we have the individual values for the year, month, and day, we can pass those in as well.

new Date(2021, 3, 20).getTime() / 1000 // 1618894800

Note that the order goes year, month, day, and only the month is zero-indexed (for absolutely no reason).

Lastly, we can also use valueOf() instead of getTime() to achieve the same result.

new Date('04-20-2021').valueOf() / 1000 // 1618894800
new Date(2021, 3, 20).valueOf() / 1000 // 1618894800

If you need to convert to a date string from an epoch, you can check out how to do that in this article.


More JavaScript Articles