How to Get a Timestamp in JavaScript

Timestamps in JavaScript are used to represent a specific point in time, typically expressed in milliseconds or seconds since the Unix epoch (January 1, 1970 00:00:00 UTC).

In this Javascript tutorial, we’ll explore various ways to get timestamps in JavaScript.


Creating a Timestamp in JavaScript

JavaScript provides the Date object to work with dates and times.

You can create a new Date object and use its .getTime() method to get the timestamp in milliseconds.

Here’s an example:

let now = new Date();
let timestamp = now.getTime();
console.log(timestamp);

Another way to get the timestamp is to use the Date.now() method, which returns the current time in milliseconds since the Unix epoch.

Here’s an example:

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

Converting a Timestamp to a Date

If you have a timestamp, you can convert it to a Date object using the new Date(timestamp) constructor.

Here’s an example:

let timestamp = 1609459200000;
let date = new Date(timestamp);
console.log(date);

Formatting Timestamps

By default, the Date object provides a string representation of the date and time in the format “Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)”.

You can use the .toLocaleString() method to format the timestamp to a more human-readable format.

Here’s an example:

let now = new Date();
let formattedTimestamp = now.toLocaleString();
console.log(formattedTimestamp);

Conclusion

In this tutorial, we have learned various ways to get timestamps in JavaScript using the Date object.

We have also seen how to convert a timestamp to a Date object and format it to a more readable format.

Timestamps are an important aspect of working with dates and times in JavaScript and can be used in various applications to track time-sensitive events.