Hello im about the compare two dates in javascript with each other
for example consider this two value : date1 = 2024-5-13T20:30:00 and date2 = 2024-5-13T21:30:20
the day and month is the same but the hours is diffrent
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
please help me to solve this issue
the method i used first time : date1.toISOString().split(‘T’)[0] === date2.toISOString().split(‘T’)[0]
this method is not suitable for me beacuase its loop between the characters of time string then split and its reduce the performance
dariush jokar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4
Just compare year/month/date:
const date1 = new Date('2024-05-13T20:30:00'), date2 = new Date('2024-05-13T21:30:20');
const isSameDate = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
console.log(isSameDate(date1, date2));
Another option is to cut time which has more speed potential:
const date1 = new Date('2024-05-13T20:30:00'), date2 = new Date('2024-05-13T21: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(isSameDate(date1, date2));
Let’s benchmark:
` Chrome/124
-----------------------------------------------------
cut time ■ 1.00x | x1000000000 327 333 334 338 338
getXXX() 25.87x | x100000000 846 847 856 861 876
Wimanicer 3333.33x | x100000 109 110 111 113 123
-----------------------------------------------------
https://github.com/silentmantra/benchmark `
The cutting time is a winner…
const date1 = new Date('2024-05-13T20:30:00'), date2 = new Date('2024-05-13T21:30:20');
// @benchmark Wimanicer
const isSameDate0 = (a, b) => a.toLocaleDateString() === b.toLocaleDateString();
// @run
isSameDate0(date1, date2);
// @benchmark getXXX()
const isSameDate = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
// @run
isSameDate(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));
3
Using toLocaleDateString is a fast way to check this:
const date1 = new Date('2024-05-13T20:30:00'), date2 = new Date('2024-05-13T21:30:20');
const isSameDate = (a, b) => a.toLocaleDateString() === b.toLocaleDateString();
console.log(isSameDate(date1, date2));