How to get current epoch timestamp in javascript


In this post, You will learn multiple ways to get current epoc timestamp in javascript.

epoch time is Unix style in milli seconds since 01/01/1971, that means it returns long number in milli seconds, This is epoch time or unix timestamp

Javascript provides Date object provides date and time related things.

Note: Javascript runs on client and server side. 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 to good to have a return the server side timestamps only

get time in milliseconds from Unix epoch time in javascript

First, Create an Date object in javascript returns current date and time.

console.log(new Date())// get current date and time

getTime() method in Date object returns long number, which is milliseconds elapsed from 1/1/1971 UTC time.

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();
  };
}

There another way to get timestamp with valueOf method

new Date().valueOf() 

Get timestamp in seconds

getTime() or now() returns time in milliseconds, One second is equal to 1000 milliseconds,

Use divide operator to get the seconds.

Example:

console.log(Math.floor(new Date().getTime() / 1000));
console.log(Math.floor(Date.now() / 1000));
THE BEST NEWSLETTER ANYWHERE
Join 90,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts