Explain Codes LogoExplain Codes Logo

Comparing date part only without comparing time in JavaScript

javascript
date-comparison
javascript-utility
best-practices
Alex KataevbyAlex Kataev·Nov 15, 2024
TLDR

Compare date parts without time by setting time to 0 on both dates and comparing the timestamps:

const date1 = new Date('2023-03-25'); const date2 = new Date('2023-03-25'); const isSameDay = (d1, d2) => d1.setHours(0, 0, 0, 0) === d2.setHours(0, 0, 0, 0); console.log(isSameDay(date1, date2)); // true, apparently they're twins

In essence, setHours(0, 0, 0, 0) sets both dates to midnight, eliminating time from the equation before the timestamp comparison using ===.

Dealing with tricky timezones

When dealing with different timezones, it's important to bring everything to a common ground. Here, we convert both dates to UTC:

const isSameDayUTC = (d1, d2) => { let date1UTC = Date.UTC(d1.getFullYear(), d1.getMonth(), d1.getDate()); let date2UTC = Date.UTC(d2.getFullYear(), d2.getMonth(), d2.getDate()); return date1UTC === date2UTC; // Red rover, red rover, send the matching date right over };

This approach takes into account the timezone discrepancies ensuring an accurate comparison even in the face of global diversity.

Comparing Serialized Dates

Yet another approach lies in serializing the dates into a string format for comparison:

const serializeThisDate = (date) => date.toISOString().split('T')[0]; console.log(serializeThisDate(date1) === serializeThisDate(date2)); // true, they're not just siblings, they're twins

Here, we avoid messing with the actual date objects by comparing serialized date strings. It's as easy as comparing apples to apples.

Extended Date Object Comparison

You might find yourself repeatedly comparing dates throughout your codebase. In such cases, extending the Date object with a custom method becomes handy:

Date.prototype.withoutTime = function() { let d = new Date(this); d.setHours(0, 0, 0, 0); return d; // Back to the future... kind of }; console.log(date1.withoutTime().getTime() === date2.withoutTime().getTime()); // true, it's a match made in heaven... well, in code

This prototype expansion allows for more readable and concise code when repetitive date comparisons are needed.

Using Third-Party Libraries

For more complex date manipulations, third-party libraries like Moment.js are a godsend:

const moment = require('moment'); const areTheyTwins = (d1, d2) => moment(d1).isSame(d2, 'day'); console.log(areTheyTwins(date1, date2)); // true, yes they are

Using Moment.js, you get to enjoy a more concise and friendly syntax, with an array of additional features at your disposal.

String Comparison Approach

An alternate approach is to compare the string representation of the dates:

console.log(date1.toDateString() === date2.toDateString()); // true, another win for the twins

Here, toDateString() converts the dates into a human-readable form without time, facilitating an easy comparison.

Warning: Precision Pitfalls

Direct comparison of dates without proper handling can lead to precision problems. Serialization of dates might gloss over details like leap seconds or daylight saving changes. Therefore, ensure to maintain a consistent representation for date comparisons to keep things accurate.

Be Cautious of Console Display

The way dates are displayed in console can lead to misinterpretation. Browsers may serialize them into a string representing the local timezone. Always verify the actual value of date objects in your comparisons, because perception isn't always reality.