Step 1: Convert Unix timestamp to milliseconds
To convert the timestamp to milliseconds, multiply the input by 1000 to get the milliseconds.
const unixTimestamp = 1575909015 const milliseconds = unixTimestamp * 1000 console.log(milliseconds)
We get the milliseconds from the timestamp by multiplying it by 1000.
Step 2: Convert milliseconds to Date object
Let’s continue with the above example. We got the output:
1575909015000 after converting it into milliseconds. Let’s convert this into a Date object.
const unixTimestamp = 1575909015 const milliseconds = unixTimestamp * 1000 const dateObject = new Date(milliseconds) console.log(dateObject)
- The new Date() constructor takes a millisecond as an argument. To get the millisecond as an argument, multiply the Unix timestamp by 1000.
- To create a Date object, use the new Date() constructor. The Date object in the given code will describe a single moment in time and represent data in the form of year, month, day, hour, minute, and second for a moment.
- In the end, we are left will the dateObject variable, which represents the data object instance. We will use it in the final step.
Step 3: Convert dateObject to human-readable date format
Let’s continue with our example; in the previous step, we got
2019-12-09T16:30:15.000Zas output. Let’s pass this output to the toLocaleString() function and get the final human-readable Date we need for this example.
const unixTimestamp = 1575909015 const milliseconds = unixTimestamp * 1000 const dateObject = new Date(milliseconds) const humanDateFormat = dateObject.toLocaleString() console.log(humanDateFormat)
12/9/2019, 10:00:15 PM
- We created a human-friendly date string using the toLocaleString() function on the dateObject.
- The toLocaleString() function can be called on a dateObject and returns the string. We finally get a Date from the timestamp in a human-readable format.
Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.