JavaScript How to Convert Date to Timestamp Easily
date.getTime() or Date.parse(dateString) which returns the number of milliseconds since January 1, 1970.Examples
How to Think About It
getTime() on a Date object or by parsing a date string with Date.parse().Algorithm
Code
const date = new Date('2024-06-01T00:00:00Z'); const timestamp = date.getTime(); console.log(timestamp);
Dry Run
Let's trace converting '2024-06-01T00:00:00Z' to timestamp using getTime()
Create Date object
date = new Date('2024-06-01T00:00:00Z') // represents June 1, 2024 at midnight UTC
Get timestamp
timestamp = date.getTime() // returns 1716998400000 milliseconds
Output timestamp
console.log(timestamp) // prints 1716998400000
| Step | Action | Value |
|---|---|---|
| 1 | Create Date object | 2024-06-01T00:00:00.000Z |
| 2 | Call getTime() | 1716998400000 |
| 3 | Print timestamp | 1716998400000 |
Why This Works
Step 1: Date object stores time
A JavaScript Date object holds a specific moment in time internally as milliseconds from January 1, 1970.
Step 2: getTime() returns milliseconds
Calling getTime() on a Date object returns this internal millisecond count, which is the timestamp.
Step 3: Date.parse() parses strings
Date.parse() converts a date string directly into the same millisecond timestamp number.
Alternative Approaches
const timestampNow = Date.now(); console.log(timestampNow);
const date = new Date('2024-06-01T00:00:00Z'); const timestamp = +date; console.log(timestamp);
Complexity: O(1) time, O(1) space
Time Complexity
Getting a timestamp from a Date object is a direct operation with no loops, so it runs in constant time O(1).
Space Complexity
No extra memory is needed beyond the Date object and a number variable, so space complexity is O(1).
Which Approach is Fastest?
getTime() and unary plus are equally fast; Date.parse() parses strings and may be slightly slower but still O(1).
| Approach | Time | Space | Best For |
|---|---|---|---|
| date.getTime() | O(1) | O(1) | Converting Date objects to timestamp |
| Date.parse() | O(1) | O(1) | Converting date strings to timestamp |
| Unary plus (+date) | O(1) | O(1) | Short syntax for Date to timestamp |
| Date.now() | O(1) | O(1) | Getting current timestamp only |
date.getTime() to get the timestamp in milliseconds from any Date object.