How to Get a Timestamp in Javascript?
To get a timestamp in Javascript, you can use the getTime()
method of the Date
object. This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
Here's an example:
const timestamp = new Date().getTime();
console.log(timestamp); // 1622728812157
You can also use the Date.now()
method, which is a shorthand for new Date().getTime()
. Here's an example:
const timestamp = Date.now();
console.log(timestamp); // 1622728812157
Note that the value returned by getTime()
or Date.now()
is a number, not a string. If you need to convert it to a string, you can use the toString()
method or the String()
constructor. Here's an example:
const timestamp = new Date().getTime().toString();
console.log(timestamp); // "1622728812157"
const timestampString = String(timestamp);
console.log(timestampString); // "1622728812157"