Converting milliseconds to a date in JavaScript means converting a timestamp representing the number of milliseconds since January 1, 1970, 00:00:00 UTC into a readable date and time. The Date object can directly convert a millisecond timestamp into a date.
- Use new Date() to create a Date object from a millisecond timestamp.
- Use getTime() to obtain the current date and time in milliseconds.
- Use toString() to display the resulting Date object as a readable string.
Approach 1: Using Date() Constructor with getTime()
The Date() constructor can accept a millisecond timestamp and return the corresponding date and time. First, obtain the current time in milliseconds using getTime(), then pass that value to new Date().
Example: In this example, the current date and time are converted into milliseconds and then converted back into a readable date.
// Get the current time in milliseconds
let time = new Date().getTime();
// Convert milliseconds to a Date object
let date = new Date(time);
console.log("Date = " + date.toString());
Approach 2: Using a Given Millisecond Timestamp
A specific millisecond timestamp can also be directly passed to the Date() constructor. JavaScript interprets the value as milliseconds elapsed since January 1, 1970, 00:00:00 UTC.
Example: In this example, a given millisecond timestamp is converted into a readable date.
let milliseconds = 1578567991011;
// Convert milliseconds to a Date object
let date = new Date(milliseconds);
console.log("Date = " + date.toString());