Get a timestamp in JavaScript

In this tutorial, we will see how to get timestamp in JavaScript.

In JavaScript, we can get a timestamp in various ways depending on our requirements. A timestamp represents the number of milliseconds since January 1, 1970 (Coordinated Universal Time), which is often referred to as “Unix time”.

Here are several methods to get a timestamp in JavaScript.

Get timestamp in milliseconds

Now, have a look at the methods below to get timestamp in milliseconds in JavaScript.

Using Date object

The Date() object is a built-in JavaScript object that provides date and time information. We can get a timestamp using the getTime() method.

Example

const timestamp = new Date().getTime(); // Current timestamp in milliseconds
console.log("Timestamp:", timestamp);

In the above program, I have created a new Date object, which represents the current date and time.

Then, I have called the getTime() method on the Date object to retrieve the timestamp in milliseconds.

Output:

Timestamp: 1698126682897

Using Date.now method

The Date.now method is a convenient method of JavaScript. This method directly returns the current timestamp in milliseconds.

Example

const timestamp = Date.now(); // Current timestamp in milliseconds
console.log("Timestamp:", timestamp);

In the above program, the Date.now() will return the current timestamp in milliseconds directly.

Output:

Timestamp: 1698127486523

Using the Unary Plus (+) Operator

We can use the unary plus (+) operator to convert a Date object to a timestamp.

Example

const timestamp = + new Date() // Current timestamp in milliseconds
console.log("Timestamp:", timestamp);

In the above program, I have created a Date object and then used the unary plus (+) operator to convert it into a numeric value, which represents the timestamp in milliseconds.

Output:

Timestamp: 1698128009825

Using performance.now() method

We can use the performance.now() method to get high-resolution time.  This method provides timestamp in milliseconds.

Example:

const timestamp = performance.now() // Current timestamp in milliseconds
console.log("Timestamp:", timestamp);

In the above program, the performance.now() will return a high-resolution timestamp in milliseconds.

Timestamp in seconds

Now, If we want to get a timestamp in seconds rather than milliseconds, we can use JavaScript’s Date object and then convert the milliseconds to seconds.

Example

const timestamp = Math.floor(Date.now() / 1000); 
console.log("Timestamp:", timestamp);

In the above program, I have used Date.now() to get current timestamp in milliseconds.

Then, I have divided the value by 1000 to convert milliseconds to seconds.

And the Math.floor() is used to round the the nearest whole second.

Output:

Timestamp: 1698132754

 

Leave a Reply

Your email address will not be published. Required fields are marked *