Date class provides methods to interact with dates and times. Usually, you need to put more effort into calculating the value that you’re interested in.
Node.js Series Overview
- Callback and Promise Support in your Node.js Modules
- Increase the Memory Limit for Your Process
- Why You Should Add “node” in Your Travis Config
- Create a PDF from HTML with Puppeteer and Handlebars
- Create Your Own Custom Error
- Extend Multiple Classes (Multi Inheritance)
- Get a File’s Created Date
- Get a File’s Last Modified/Updated Date
- Human-Readable JSON.stringify() With Spaces and Line Breaks
- Write a JSON Object to a File
- How to Create an Empty File
- Run Async Functions/Promises in Sequence
- Run Async Functions/Promises in Parallel
- Run Async Functions in Batches
- How to Merge Objects
Here’s a code snippet showing you how to get the number of seconds since epoch:
const now = new Date() const secondsSinceEpoch = Math.round(now.getTime() / 1000)
.getTime() call retrieves the milliseconds since epoch in UTC.
Convert them to seconds by dividing by 1000. This may create a decimal and you have to ensure an integer value by rounding to the next whole number. Otherwise, you may run into odd behavior when using the decimal value.
Can You Use Date.now()?
Date.now() also returns the milliseconds since epoch:
const secondsSinceEpoch = Math.round(Date.now() / 1000)
The difference between
new Date().getTime() and
Date.now() is that
Date.now()returns the milliseconds since epoch for your timezone
new Date().getTime()always returns the UTC milliseconds
We like to go with
.getTime() to ensure we’re always calculating with UTC timestamps.