Define Age based on date range

Hello World,

i got a question about date range

example : a kid is born 15th of February year 2009 Time 6am, 15/2/2009, if calculate as at today (17/1/2022), his age is still consider 12, and will be only consider age 13 after 15/2/2022 6am,

how can i make it into a calculation ?

regards

Hi
consider using date-fns

Lot’s of complexities you don’t want to figure out yourself if it comes to dealing with dates.

hello Tommertom, happy new year 2022

thank you i will take a look

thanks

:bowing_woman: :bowing_woman: :bowing_woman:

If you’re planning on releasing this app to a broad audience, beware that different cultures have different methods of calculating age. I would take special care to wall this calculation completely off into a single place, so that it can be modified according to locale or user preference without requiring major refactoring of the app.

Yes Sir! noted of age calculation! :bowing_man:

This is a great question and one that comes up frequently when building date-based features. The key challenge you’ve identified—calculating based on both date and time—is exactly what makes age calculations tricky.

For anyone building a similar feature and wanting to verify their logic or just get a quick reference, I often use this tool to cross-check the calculation: age

The date-fns library Tommertom recommended is indeed a solid choice for handling these complexities in JavaScript. It handles timezone issues and the exact moment-based logic you’re describing (like turning 13 at exactly 6am on the birthday).

I’d also second rapropos’s point about cultural differences. Some cultures consider a person to be 1 year old at birth, while others use the Western system where age increments on the birthday. If you’re building for a global audience, making that configurable is definitely worth the upfront effort.

For your specific use case with the 6am time constraint, the logic would be:

// Check if current date-time is past the birthday's exact time
const birthdayThisYear = new Date(birthday.getFullYear(), birthday.getMonth(), birthday.getDate(), 6, 0, 0);
const age = today.getFullYear() - birthday.getFullYear() - (today < birthdayThisYear ? 1 : 0);

Hope this helps anyone else who finds this thread later!