Understanding Time Value and Date Comparison in JavaScript
Learn what time value means in JavaScript and how to compare dates correctly using time values.
Understanding Time Value and Date Comparison in JavaScript
Working with dates in JavaScript can feel confusing at first, especially when you want to sort or compare them. To do this correctly, you need to understand how JavaScript stores dates internally.
JavaScript Dates Are Not Just Strings
When you write a date like "2024-01-10", it is only a string. JavaScript cannot reliably compare dates stored as strings, so we must convert them into real Date objects.
const date = new Date("2024-01-10");
What is Time Value?
When JavaScript creates a Date object, it converts the date into a large numeric value called the Time Value. This number represents the total milliseconds passed since January 1, 1970 (the Unix Epoch).
Example Time Values
| Date | Time Value (ms since 1970) |
|---|---|
| Jan 1, 1970 | 0 |
| Jan 2, 1970 | 86400000 |
| Jan 1, 2024 | 1704067200000 |
| Jan 10, 2024 | 1704758400000 |
Newer dates always have larger time values. Because of this, time values are perfect for comparing dates in JavaScript.
Getting the Time Value
const value = new Date("2024-01-10").getTime();
console.log(value);
Comparing Two Dates
const a = new Date("2024-01-01");
const b = new Date("2024-01-10");
const difference = b.getTime() - a.getTime();
- If the result is positive, b is newer.
- If the result is negative, a is newer.
Sorting Dates (Newest First)
blogPosts.sort((a, b) => {
return new Date(b.publishedAt) - new Date(a.publishedAt);
});
Final Note: If you want to compare dates, just subtract them — the newer date always has a higher time value.
Related Topics:
More Articles
OpenAI Realtime API: Build Voice Agents with WebRTC (Beginner's Guide)
Learn how to use OpenAI's Realtime API with WebRTC to build voice agents directly in the browser. A complete beginner-friendly guide with code examples.
AI Interview App: Complete Guide to Ace Your Tech Interviews
Learn how AI interview apps can help you prepare for technical interviews with real-time feedback and practice sessions.