Explain Codes LogoExplain Codes Logo

Compare two dates with JavaScript

javascript
date-handling
time-zone
date-validation
Anton ShumikhinbyAnton ShumikhinยทFeb 2, 2025
โšกTLDR

To face off two Date objects in JavaScript, put them head-to-head with comparison operators. When it comes to the crunch, Date objects morph into their timestamps, essentially their milliseconds since epoch, for accurate comparisons.

Example:

let date1 = new Date('2023-01-01'); // "New Year, same problems" ๐ŸŽŠ let date2 = new Date('2023-12-31'); // "Goodbye, cruel year!" ๐Ÿ– console.log(date1 < date2 ? "date1 is earlier" : (date1 > date2 ? "date1 is later" : "dates are equal"));

Consistent format is key here. Stick to the ISO 8601 standard (YYYY-MM-DD) to avoid tricky browser or locale differences.

Time zone & daylight saving considerations

Time zones and daylight saving โ€“ a right old pain, isn't it? If your use case asks for time zone insensitive comparisons, transfer your dates to UTC before comparing:

// "I wish I could put time in a bottle..." ๐ŸŽถ let utcDate1 = Date.UTC(date1.getUTCFullYear(), date1.getUTCMonth(), date1.getUTCDate()); let utcDate2 = Date.UTC(date2.getUTCFullYear(), date2.getUTCMonth(), date2.getUTCDate());

Too much hassle? Libraries like date-fns or moment.js bolt time zone handling onto your toolkit.

Sidestep input pitfalls

Call on dropdown selectors when you're stuck with text inputs, and keep your date inputs reliable:

// I've got 99 problems but a past date ain't one let today = new Date().toISOString().split('T')[0]; document.querySelector("#dateField").setAttribute('min', today);

Also, validate user-entered dates thoroughly to avoid unfortunate surprises.

Ensuring date validity

// Not all dates are created equal function isValidDate(d) { return d instanceof Date && !isNaN(d); } let userDate = new Date(inputString); if (!isValidDate(userDate)) { // Oops, something went sideways }

Keep it simple, silly!

Date ranges and multiple date comparisons can lead to a logic labyrinth. A helper function can help trim the complexity:

let rangeStart = new Date('2023-01-01'); let rangeEnd = new Date('2023-12-31'); function isInRange(date, start, end) { let time = date.getTime(); return time >= start.getTime() && time <= end.getTime(); } console.log(isInRange(new Date(), rangeStart, rangeEnd)); // Yay or Nay

Date comparison by the numbers

// It's like a sorting competition, but with dates function compareDates(date1, date2) { return (date1 > date2) - (date1 < date2); }

String dates and time stripping

Now, what if your dates are strings? Not all is lost! Call in an ally โ€“ new Date():

// When your date comes as a string attached let parsedDate = new Date('2023-03-10T00:00:00Z'); // ISO format

Also, strip away time if you're comparing just dates:

// Because no one asked for the time! function compareJustDates(date1, date2) { let d1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()); let d2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()); return d1.getTime() === d2.getTime(); }