
Date Arithmetic Is Harder Than It Looks: Leap Years, Timezones, and Edge Cases
"How many days between two dates" seems trivial until you encounter leap years, daylight saving transitions, timezone boundaries, and the question of whether the end date is inclusive or exclusive. Date arithmetic is one of those domains where the edge cases outnumber the normal cases. The naive subtraction problem const start = new Date ( ' 2024-03-01 ' ); const end = new Date ( ' 2024-04-01 ' ); const days = ( end - start ) / ( 1000 * 60 * 60 * 24 ); // Expected: 31. Actual: might be 30.958... due to DST If March 10 falls in this range (DST spring forward in the US), one "day" is only 23 hours. Dividing by 86,400,000 milliseconds (24 hours) gives a non-integer result. Rounding can go either direction depending on the local timezone. The correct approach for calendar day calculations is to work with dates, not timestamps: function daysBetween ( startStr , endStr ) { const start = new Date ( startStr + ' T00:00:00Z ' ); const end = new Date ( endStr + ' T00:00:00Z ' ); return Math . ro
Continue reading on Dev.to Beginners
Opens in a new tab




