How to calculate the exact age from given date until today?

How can I create a function which gives me the exact age based on the given birthdate until today? I created the following function, but the function returns me the wrong the Age. For example: if I provide dateOfBirth := 08/15/1990 and try to calculate date as of today’s date it will return 30 instead of 29. Can someone plz help me with this?

Age = math.Floor(Today.Now().Sub(*dateOfBirth).Hours() / 24 / 365)

If my birthday would be tomorrow: (20200909-19820910)/10.

There are leap years. There are time zones. There may be daylight saving time. Your Age formula is not correct.


Here is a correct calculation of age.

package main

import (
	"fmt"
	"time"
)

func age(birthdate, today time.Time) int {
	today = today.In(birthdate.Location())
	ty, tm, td := today.Date()
	today = time.Date(ty, tm, td, 0, 0, 0, 0, time.UTC)
	by, bm, bd := birthdate.Date()
	birthdate = time.Date(by, bm, bd, 0, 0, 0, 0, time.UTC)
	if today.Before(birthdate) {
		return 0
	}
	age := ty - by
	anniversary := birthdate.AddDate(age, 0, 0)
	if anniversary.After(today) {
		age--
	}
	return age
}

func main() {
	layout := "01/02/2006"
	birthdate, _ := time.Parse(layout, "08/15/1990")
	for _, today := range []string{"09/09/2020", "08/15/2020", "08/14/2020", "08/15/1991", "08/14/1991"} {
		today, _ := time.Parse(layout, today)
		fmt.Println(age(birthdate, today), birthdate.Format(layout), today.Format(layout))
	}
}
30 08/15/1990 09/09/2020
30 08/15/1990 08/15/2020
29 08/15/1990 08/14/2020
1 08/15/1990 08/15/1991
0 08/15/1990 08/14/1991

For a birth date of 08/15/1990, the first birthday is on 08/15/1991, the tenth birthday is on 08/15/2000, the thirtieth birthday is on 08/15/2020. On 09/09/2020, age is 30.

The 15th day of August 1990 was the date of birth, today os the 10th day of September 2020.

Aus September is following August, and the difference of 2020 - 1990 is 30, 30 seems indeed to be the correct result. Not sure why you expect 29.

Beyond that, a day has not always 24 hours. It can have 23 or 25 as well (DST) or even 24h+/-1 second (leap seconds). Also a year is not 365 days, it is 365.23ish days. Thats why we have an extra day in february every 4 years (skipping each 25th, but not skipping the 4th skip)…

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.