I’m working on a project where I need to find out how many days are between two dates in JavaScript. For example, if I have these dates:
let date1 = '2023-05-01 23:30:00';
let date2 = '2023-05-02 01:15:00';
Even though they’re only about 1 hour and 45 minutes apart, I want my function to return 1 day difference because they’re on different calendar days.
I’ve tried using some methods I found online, but they’re not giving me the result I’m looking for. They seem to be calculating the exact time difference instead of the day difference.
Does anyone know a reliable way to do this in JavaScript? I’d really appreciate some help or examples. Thanks!
hey there! i’ve had to deal with this before too. here’s a quick way to do it:
const daysBetween = (d1, d2) => {
let date1 = new Date(d1.substring(0, 10));
let date2 = new Date(d2.substring(0, 10));
return Math.ceil((date2 - date1) / (1000 * 60 * 60 * 24));
}
this should give u what ur looking for. it ignores the time part and just looks at the dates. hope this helps!
Here’s a neat trick I’ve used in my projects that might help you out:
function dateDiff(start, end) {
return new Date(end.split(' ')[0]) - new Date(start.split(' ')[0]) > 0 ? 1 : 0;
}
This function splits the date strings to isolate the date part, converts them to Date objects, and compares them. If the end date is greater, it returns 1; otherwise, it returns 0.
Usage:
let diff = dateDiff('2023-05-01 23:30:00', '2023-05-02 01:15:00');
console.log(diff); // Outputs: 1
It’s simple, efficient, and does exactly what you’re looking for. No need to worry about time zones or daylight savings, as long as your date strings include the ‘YYYY-MM-DD’ format for the date part.
I encountered a similar challenge in a project I worked on recently. Here’s a straightforward approach that worked well for me:
function getDayDifference(date1, date2) {
const d1 = new Date(date1).setHours(0, 0, 0, 0);
const d2 = new Date(date2).setHours(0, 0, 0, 0);
return Math.abs((d2 - d1) / (24 * 60 * 60 * 1000));
}
This function sets both dates to midnight, which effectively ignores the time component. It then calculates the difference in days.
In your case:
let date1 = '2023-05-01 23:30:00';
let date2 = '2023-05-02 01:15:00';
console.log(getDayDifference(date1, date2)); // Outputs: 1
This method has been reliable in my experience, even with daylight saving time changes. Just remember to handle potential parsing errors if your date strings might be in different formats.