In this post, You will learn multiple ways to get the current epoch timestamp in javascript.
epoch time is Unix style in milliseconds since 01/01/1971, which means it returns a long number in milliseconds. It is epoch time or Unix timestamp
Javascript provides the Date
object provides the date and time-related things.
Note: Javascript runs on the client and server sides. When you are dealing with date and time-related values, You will not get correct results as these are dependent on client machines.
It is always too good to have a return of the server-side timestamps only.
get time in milliseconds from Unix epoch time in javascript
First, Create an Date object in javascript that returns the current date and time.
console.log(new Date())// get current date and time
The getTime()
method in the Date object returns a long number, which is milliseconds elapsed from 1/1/1971 UTC.
console.log(new Date().getTime()) // number of milliseconds elapsed from epoc 1610334435379
get current UTC timestamp in javascript
console.log(Date.now());
date.now don’t have support in IE8 version or less, So you have to write a polyfill code to support it as per MDN
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
They’re another way to get a timestamp with the valueOf
method.
new Date().valueOf()
Get timestamp in seconds
getTime() or now() returns time in milliseconds, One second is equal to 1000 milliseconds,
Use the divide operator to get the seconds.
Example:
console.log(Math.floor(new Date().getTime() / 1000));
console.log(Math.floor(Date.now() / 1000));