How to get current epoch timestamp in javascript

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 to get 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 on Client side, 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.

How to get time in milliseconds from Unix epoch time in javascript

In order to get Current epoch Unix time in Javascript, Please follow below steps

  • 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
  • It returns a long number, which You can convert into seconds, divided by 1000.

How to get the current UTC timestamp in javascript

In order to get the Current UTC timestamp in Javascript, Please follow the below steps

  • date has now() function, returning the current UTC timestamp.
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();
  };
}
  • Similarly, the valueOf method is used to get a UTC timestamp.
new Date().valueOf();

How to Get UTC timestamp in seconds in typescript

To get the UTC timestamp in Seconds in typescript, Please follow the below steps

  • First, Create a Date object using the new Date()
  • next, getTime() method returns timestamp in milliseconds
  • 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));