JavaScript Converting milliseconds to date
Converting milliseconds to a date in JavaScript means transforming a millisecond timestamp (number of milliseconds since January 1, 1970, 00:00:00 UTC) into a readable date format. This is typically done using JavaScript's Date object, like new Date(milliseconds), which returns the corresponding date and time.
Approach
- First, declare variable time and store the milliseconds of the current date using the new date() for the current date and getTime() Method for returning it in milliseconds since 1 January 1970.
- Convert time into a date object and store it into a new variable date.
- Convert the date object’s contents into a string using date.toString() function
Example 1: This example first gets the milliseconds of the current date and time, Then uses that value to get the date by Date() method.
// Get the current time in milliseconds
let time = new Date().getTime();
// Convert milliseconds to a Date object
let date = new Date(time);
console.log("Milliseconds = " + date.toString());
Output
Milliseconds = Wed Sep 18 2024 03:44:17 GMT+0000 (Coordinated Universal Time)
Example 2: This example first gets the random milliseconds(1578567991011 ms), Then uses that value to get the date by Date() method.
let milliseconds = 1578567991011;
// Convert milliseconds to a Date object
let date = new Date(milliseconds);
console.log("Milliseconds = " + date.toString());
Output
Milliseconds = Thu Jan 09 2020 11:06:31 GMT+0000 (Coordinated Universal Time)
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.