Back to Blog
3 min read

How to Calculate Age in Go (time.Time and Birthday Logic Examples)

Learn how to calculate age from date of birth in Go using time.Time. Includes completed years, as-of date logic, leap year notes, and copy ready examples.

How to Calculate Age in Go (time.Time and Birthday Logic Examples)

How to Calculate Age in Go (time.Time and Birthday Logic Examples)

If you need to calculate age in Go, the key is to count completed years, not just subtract birth year from current year. You also need to handle birthdays that have not happened yet this year.

Fast answer

If you need a quick result or want to test your logic, use the online age calculator first, then mirror the same rules in code.

Basic Go function for completed years

package main

import (
    "fmt"
    "time"
)

func AgeYears(dob time.Time, asOf time.Time) int {
    years := asOf.Year() - dob.Year()

    hadBirthday := asOf.Month() > dob.Month() ||
        (asOf.Month() == dob.Month() && asOf.Day() >= dob.Day())

    if !hadBirthday {
        years--
    }

    return years
}

func main() {
    dob := time.Date(1998, time.October, 12, 0, 0, 0, 0, time.UTC)
    asOf := time.Date(2026, time.March, 19, 0, 0, 0, 0, time.UTC)
    fmt.Println(AgeYears(dob, asOf))
}

Use the same location for both dates

In Go, time zones matter. If DOB is stored in one location and asOf is built in another, day boundaries can shift. For date of birth checks, create both values in the same location and usually at midnight.

loc, _ := time.LoadLocation("Europe/Warsaw")
dob := time.Date(2000, time.February, 29, 0, 0, 0, 0, loc)
asOf := time.Now().In(loc)

Age as of a specific date

Many business rules need age on a fixed date, not just today: school eligibility, insurance, forms, and reports. Pass that date explicitly instead of calling time.Now() inside your age function.

Leap year note

For birthdays on Feb 29, decide how your app should behave in non leap years. Some systems treat Feb 28 as the comparison date, others use Mar 1. Document the rule and test it.

FAQ

Why is asOf.Year() - dob.Year() not enough?

Because it ignores whether the birthday already happened this year. You need one more comparison on month and day.

Should I use time.Now() inside the function?

Usually no. Passing an explicit asOf date makes tests easier and avoids hidden time zone surprises.

Related