Counting calendar days in JavaScript without off-by-one errors
Calculating the number of days between two dates in JavaScript is trickier than it looks, due to time zones, daylight saving time, and how the Date object parses strings. Subtracting local-midnight timestamps across a clock change yields a 23- or 25-hour day, producing fractional or wrong results. Date-only ISO strings are parsed as UTC while date-time strings are parsed as local time, which can shift the day for some users. The suggested fix is to strip the time and zone by building UTC midnight from each date's calendar parts, parsing YYYY-MM-DD strings manually, and using Intl.DateTimeFormat to determine the user's current day in a given time zone. The author tested these approaches in Node 20.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in