Creating Dates from Milliseconds Since Epoch
You'll learn how to create JavaScript Date objects from Unix timestamps using milliseconds since the epoch.
What Is the Epoch?
The "epoch" is a specific point in time: January 1, 1970, 00:00:00 UTC. This date serves as time zero for computers. Think of it like setting a stopwatch to zero before a race—every moment after is measured from that starting point.
Creating Dates from Milliseconds
You can create a Date object by passing the number of milliseconds since the epoch to the Date constructor:
// 1000 milliseconds = 1 second after epoch
const oneSecondAfter = new Date(1000);
console.log(oneSecondAfter);
// Thu Jan 01 1970 00:00:01 GMT...
// One day = 86,400,000 milliseconds
const oneDayAfter = new Date(86400000);
console.log(oneDayAfter);
// Fri Jan 02 1970 00:00:00 GMT...
// Current timestamp (common real-world scenario)
const someDate = new Date(1609459200000);
console.log(someDate);
// Fri Jan 01 2021 00:00:00 GMT...
Why Use Milliseconds?
Timestamps in milliseconds are universal, compact, and easy to store in databases or transmit over networks. They're just numbers, making them simple to compare, add, or subtract.
Negative numbers represent dates before the epoch:
const beforeEpoch = new Date(-86400000);
console.log(beforeEpoch);
// Wed Dec 31 1969 00:00:00 GMT...
Key Takeaway: Use new Date(milliseconds) to create dates from Unix timestamps, where milliseconds are counted from January 1, 1970 UTC (the epoch). This format is the standard for representing time in programming.