Menu

I Tried to Calculate Age Between Two Dates… It’s More Annoying Than You Think
📰

I Tried to Calculate Age Between Two Dates… It’s More Annoying Than You Think

DEV Community·Helge Andresen·6 months ago
#mfbbrcCt
#coding#javascript#datetime#webdev#years
Reading 0:00
15s threshold

I needed a simple thing the other day:

“What’s the exact age between two dates?”

Not just years. I wanted the full breakdown—years, months, days.

Should be easy, right?

Yeah… not really.

The “simple” approach (that breaks quickly)

My first instinct was:

const now = new Date();

const birth = new Date("1990-01-01");

const years = now.getFullYear() - birth.getFullYear();

Done?

Not even close.

This ignores:

Whether the birthday has happened yet this year

Month differences

Day differences

Leap years

So you end up with something that’s almost right… which is the worst kind of wrong.

The real problem: dates are messy

Once you try to do it properly, you run into edge cases:

Months have different lengths

February exists (and sometimes has 29 days)

You have to “borrow” days from previous months

Timezones can mess with exact values

At that point it stops being a quick calculation and turns into… date logic hell.

A slightly better approach

Here’s a more correct (but still simplified) way to…

Continue reading — create a free account

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