How do you get a timestamp in JavaScript?

The timestamp plays a vital role in log messages, denoting the precise moment an event transpired, typically including the date and time of day, and occasionally even accurate down to fractions of a second. Date libraries available in various programming languages significantly streamline essential tasks related to date parsing, date arithmetic, logical operations, and date formatting. These libraries offer developers robust tools to effectively manage and manipulate date-related data, facilitating more efficient and error-free handling of temporal information in software applications.

JavaScript Timestamp

when a unary operator like the plus (+) sign is used with a Date object, it invokes the valueOf() method of the Date object. This method returns the timestamp representation of the Date object, which is the number of milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC).


+ new Date()

example
console.log(+ new Date());
Output:
1637903389713

To get the timestamp in seconds, you can use:

console.log(+ new Date()/1000);

Also, the current timestamp can be fetched by calling the now() method on the Date object:


Date.now()

example
console.log(Date.now());
Output:
1637903473502

To get the timestamp in seconds, you can use:

Math.floor(Date.now() / 1000)

The same output you get by calling:

console.log(new Date().getTime());
Output:
1637903827890


Javascript timestamp

How to get the UNIX timestamp in JavaScript?

The getTime() method returns the millisecond representation.


(new Date()).getTime()

You can divide it by 1000 for get the representation in seconds.

console.log((new Date()).getTime() / 1000);
Output:
1637903866.718

Also, you can type date +%s in the terminal and get the UNIX timestamp.

$ date +%s

Conclusion

This timestamp is useful for various purposes, such as measuring time intervals, creating unique identifiers, or working with dates and times in JavaScript. Keep in mind that the value will be continually changing as it represents the current time.