Menu

Counting the days between two dates is harder than it looks
📰

Counting the days between two dates is harder than it looks

DEV Community: tutorial·MultiCalify·about 3 hours ago
#a4Fn3adb
#devtotutorial#devto#dev#date#days
Reading 0:00
15s threshold

"How many days between these two dates?" sounds like a one-liner. Subtract, divide by 86,400,000, done. It works in most tests you will write, which is exactly why it ships with a bug.

I have been building small date and money calculators, and the date ones have produced more "wait, that's wrong" moments than anything else. Here are the four places it breaks, with outputs I ran myself (Node 24), and a version that does not.

The naive version

const MS_PER_DAY = 24 * 60 * 60 * 1000 ;

function naiveDays ( a , b ) { return Math . floor ( ( b - a ) / MS_PER_DAY ) ; }

Enter fullscreen mode

Exit fullscreen mode

Fine in a quick test. Now run it in a machine set to US Eastern time:

const a = new Date ( 2026 , 2 , 1 ) ; // March 1, 2026, local midnight const b = new Date ( 2026 , 2 , 31 ) ; // March 31, 2026, local midnight

( b - a ) / MS_PER_DAY // 29.958333333333332 naiveDays ( a , b ) // 29

Enter fullscreen mode

Exit fullscreen mode

March 1 to March 31 is 30 days.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.