How to Get the Current Timestamp in JavaScript
In this tutorial, you'll learn about timestamps and how to get the current timestamp in JavaScript using the built-in Date
object.
What is a Timestamp?
A UNIX timestamp, also known as Epoch time, is a positive integer representing the number of seconds that have elapsed since January 1st, 1970, at midnight.
JavaScript takes this one step further by appending an additional three digits to the integer, representing the time elapsed in milliseconds.
Get the Current Timestamp
There are three ways to get the current timestamp in JavaScript, all of which use the built-in Date
object and return the same value:
new Date().getTime()
new Date().valueOf()
Date.now()
Traditionally, web programming languages output timestamps in seconds instead of milliseconds. If you need to convert your timestamp to display in seconds, you can run a quick calculation:
Math.floor(Date.now() / 1000)
Since 1 second equals 1,000 milliseconds, we divide the timestamp returned from JavaScript by 1000 to get the desired result.
Including the Math.floor()
function ensures your timestamp is not a decimal value and does not jump ahead by rounding up one second.
Get the Current Date from a Timestamp
Alternatively, if you have a timestamp and need to convert it to a readable date, you can do so with this code snippet:
new Date([timestamp])
// Sat Aug 13 2022 14:33:02 GMT-0600 (Mountain Daylight Time)
You'll need to ensure that the value you're passing into the Date()
function is a valid integer. By passing a string into this function, you'll receive an error. If you're not sure of the datatype and want to provide a failsafe, you can always use the parseInt()
function.
Conclusion
This quick tutorial walked you through timestamps and how to use them in JavaScript with the Date
object. It also covered converting timestamps from integer values to human-readable dates.
Created: August 13, 2022
Comments
There are no comments yet. Start the conversation!