Compare Two Dates, Ignoring Time, in JavaScript

Dec 4, 2020

To compare two dates, ignoring differences in hours, minutes, or seconds, you can use the toDateString() function and compare the strings:

const d1 = new Date('2020-06-01T12:00:00.000Z');
const d2 = new Date('2020-06-01T12:30:00.000Z');
const d3 = new Date('2020-05-01T12:00:00.000Z');

d1.toDateString() === d2.toDateString(); // true
d1.toDateString() === d3.toDateString(); // false

The more nuanced question is which timezone you want to compare the dates in. The toDateString() function calculates the date in the server's local timezone. In order to compare dates in UTC time as opposed to server local time, you can use the toUTCString() function and slice() the result to just compare the date portion:

const d1 = new Date('2020-06-01T00:00:01.000Z');
const d2 = new Date('2020-06-01T02:00:00.000Z');
const d3 = new Date('2020-05-31T23:59:59.000Z');

// The first part of the `toUTCString()` output format according to:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
const format = 'Www, dd Mmm yyyy';
d1.toUTCString().slice(0, format.length) === d2.toUTCString().slice(0, format.length); // true
d1.toUTCString().slice(0, format.length) === d3.toUTCString().slice(0, format.length); // false

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!