I am about the compare two dates in JavaScript with each other for example consider this two value :
date1 = 2024-5-13T20:30:00
date2 = 2024-5-13T21:30:20
the day and month is the same but the hours is different
my goal is to return true for each day that have the same value as month and year and ...
its should compare the date in the format yyyy/mm/dd
the method I used first time :
date1.toISOString().split('T')[0] === date2.toISOString().split('T')[0]
this method is not suitable for me because its loop between the characters of time string then split and its reduce the performance
Cut time in UTC:
const date1 = new Date('2024-05-13T23:30:00'), date2 = new Date('2024-05-14T00:30:20');
const DAY_TIME = 3600 * 24 * 1000;
const isSameDate = (a, b) => (a = a.getTime(), b = b.getTime(), (a - a % DAY_TIME) === (b - b % DAY_TIME));
console.log(date1.toLocaleString(), '-', date2.toLocaleString());
console.log(isSameDate(date1, date2));
Cut time in local timezone:
const date1 = new Date('2024-05-13T23:30:00'), date2 = new Date('2024-05-14T00:30:20');
const DAY_TIME = 3600 * 24 * 1000;
const offset = date1.getTimezoneOffset() * 60000;
const isSameDate = (a, b) => (a = a.getTime() - offset, b = b.getTime() - offset, (a - a % DAY_TIME) === (b - b % DAY_TIME));
console.log(date1.toLocaleString(), '-', date2.toLocaleString());
console.log(isSameDate(date1, date2));
Let's benchmark:
` Chrome/124
----------------------------------------------------------
cut time ■ 1.00x | x1000000000 335 337 342 347 363
Wimanicesir 3373.13x | x100000 113 116 119 123 146
DateTimeFormat 3820.90x | x100000 128 128 132 136 141
---------------------------------------------------------- `
const date1 = new Date('2024-05-13T20:30:00'), date2 = new Date('2024-05-13T21:30:20');
// @benchmark Wimanicesir
const isSameDate0 = (a, b) => a.toLocaleDateString() === b.toLocaleDateString();
// @run
isSameDate0(date1, date2);
// @benchmark DateTimeFormat
const {format} = Intl.DateTimeFormat('en-US');
const isSameDate1 = (a, b) => format(a) === format(b);
// @run
isSameDate1(date1, date2);
// @benchmark cut time
const DAY_TIME = 3600 * 24 * 1000;
const isSameDate2 = (a, b) => (a = a.getTime(), b = b.getTime(), (a - a % DAY_TIME) === (b - b % DAY_TIME));
// @run
isSameDate2(date1, date2);
/*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));