To get a timestamp in JavaScript, you can use the Date
object and its getTime
method.
Here’s an example of how you can use the Date
object and the getTime
method to get a timestamp:
const timestamp = new Date().getTime(); console.log(timestamp); // 1623129877363
This will get the current date and time and return the timestamp in milliseconds.
You can also use the Date
object and the getTime
method to get a timestamp for a specific date and time:
const date = new Date('2022-12-31'); const timestamp = date.getTime(); console.log(timestamp); // 1644731200000
This will get the timestamp for the date and time specified in the Date
object.
Keep in mind that the timestamp is the number of milliseconds since January 1, 1970, 00:00:00 UTC. You can use the toString
method of the Date
object to convert the timestamp to a human-readable date and time.
const date = new Date(timestamp); console.log(date.toString()); // Fri Dec 31 2022 00:00:00 GMT+0000 (Greenwich Mean Time)
This will convert the timestamp to a human-readable date and time string.