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
- 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
- Write a JSON Object to a File
- How to Create an Empty File
- How to Merge Objects
- Retrieve a Request’s IP Address in Node.js
- Detect the Node.js Version in a Running Process or App
- String Replace All Appearances
- How to Run an Asynchronous Function in Array.map()
- How to Reset and Empty an Array
- for…of vs. for…in Loops
- Get an Array With Unique Values (Delete Duplicates)
- Callback and Promise Support in your Node.js Modules
- Run Async Functions/Promises in Sequence
- Run Async Functions/Promises in Parallel
- Run Async Functions in Batches
Here’s a code snippet showing you how to get the number of seconds since epoch:
const secondsSinceEpoch = Math.round(Date.now() / 1000) // is the same as const now = new Date() const secondsSinceEpoch = Math.round(now.getTime() / 1000)
new Date().getTime() calls retrieve the milliseconds since the UTC epoch.
Convert the milliseconds since epoch 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.
How to Retrieve the UTC Seconds Since Epoch?
You may want to keep all dates in UTC format when working with them. Calculating the number of seconds since epoch using
Date.now() results in a date in your local timezone.
Here’s how to retrieve the number of seconds since epoch in UTC:
const now = new Date() const utcMilllisecondsSinceEpoch = now.getTime() + (now.getTimezoneOffset() * 60 * 1000) const utcSecondsSinceEpoch = Math.round(utcMilllisecondsSinceEpoch / 1000)
utcSecondsSinceEpoch variable contains the number of seconds elapsed since epoch and the current date, in UTC.
date.getTimezoneOffset() returns the timezone difference of your current locale (host system settings) to UTC in minutes. You must then transform the minutes into milliseconds to calculate with the same units.