Open In App

How to get the timestamp in JavaScript ?

Last Updated : 12 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a timestamp is a numeric representation of the current time. It is a unique identifier that marks the exact moment when an event occurred or when a certain action was performed. This timestamp is useful in various applications such as logging, debugging, or measuring time intervals. In this article, we will explore different approaches to getting a timestamp in JavaScript.

Below are the approaches used to get the timestamp in JavaScript:

Using Date.now() method

This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. It is a static method of the Date object and is widely supported by modern browsers.

Syntax:

let timestamp = Date.now();

Example: In this example, timestamp will hold the current timestamp in milliseconds, and it will be logged to the console. If you want the timestamp in seconds, you can divide the result by 1000:

Javascript




const timestamp = Date.now();
console.log(timestamp);


Output

1704968831494

Using new Date().getTime() method

This method also returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. It is an instance method of the Date object and is equivalent to calling the valueOf() method.

Syntax:

let timestamp = new Date().getTime();

Example 2: In this example, the new Date().getTime() method is used to create a new Date object and retrieve its timestamp in milliseconds. The timestamp variable will hold the current timestamp, and it will be logged to the console.

Javascript




const timestamp = new Date().getTime();
console.log(timestamp);


Output

1704968973447

Using new Date().valueOf() method

This method returns the primitive value of a Date object, which is the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Syntax:

let timestamp = new Date().valueOf();

Example: In this example, new Date().valueOf() creates a new Date object and retrieves its timestamp in milliseconds. The timestamp variable holds this value, which is then logged to the console.

Javascript




const timestamp = new Date().valueOf();
console.log(timestamp);


Output

1704969022368

Conclusion: In this article, we have discussed different approaches to getting a timestamp in JavaScript. We have seen how to use the Date.now() method, new Date().getTime() method, and new Date().valueOf() method to get a timestamp. The examples have shown how to use these methods in HTML code to display the timestamp on a webpage. Timestamps are useful in many programming scenarios, and JavaScript provides several easy-to-use methods to generate them.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads