JavaScript How to Convert Timestamp to Date Easily
new Date(timestamp) to convert a timestamp (milliseconds since Jan 1, 1970) into a JavaScript Date object, then use methods like toLocaleString() to get a readable date.Examples
How to Think About It
Algorithm
Code
const timestamp = 1672531200000; const date = new Date(timestamp); console.log(date.toLocaleString());
Dry Run
Let's trace the timestamp 1672531200000 through the code
Create Date object
new Date(1672531200000) creates a Date representing Jan 1, 2023
Convert to string
date.toLocaleString() returns '1/1/2023, 12:00:00 AM' (format depends on locale)
| Step | Value |
|---|---|
| Timestamp | 1672531200000 |
| Date object | Sun Jan 01 2023 00:00:00 GMT+0000 |
| Formatted string | 1/1/2023, 12:00:00 AM |
Why This Works
Step 1: Timestamp as milliseconds
The timestamp is the number of milliseconds since January 1, 1970, which is the standard epoch time in JavaScript.
Step 2: Date object creation
Using new Date(timestamp) creates a Date object representing that exact moment in time.
Step 3: Formatting date
Calling toLocaleString() on the Date object converts it into a readable string based on your computer's locale settings.
Alternative Approaches
const timestamp = 1672531200000; const date = new Date(); date.setTime(timestamp); console.log(date.toString());
const timestamp = 1672531200000; const date = new Date(timestamp); const formatter = new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long' }); console.log(formatter.format(date));
Complexity: O(1) time, O(1) space
Time Complexity
Creating a Date object and formatting it takes constant time, as no loops or recursion are involved.
Space Complexity
Only a few variables are used, so space usage is constant.
Which Approach is Fastest?
Using new Date(timestamp) directly is the simplest and fastest way; alternatives add formatting flexibility but with minor overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| new Date(timestamp) | O(1) | O(1) | Simple conversion |
| Date.setTime() | O(1) | O(1) | Reusing Date objects |
| Intl.DateTimeFormat | O(1) | O(1) | Custom date formatting |