Welcome To Golang By Example

Get age given a DOB in Go (Golang)

This tutorial will talk about how given a date of birth we can compute the age of a person. go-age comes to our rescue for doing that. It also takes into account the complexities of leap year while calculating age.

See a below working example:

package main

import (
    "fmt"
    "time"
    age "github.com/bearbin/go-age"
)

func main() {
    dob := getDOB(2011, 4, 2)
    fmt.Printf("Age is %d\n", age.Age(dob))
}

func getDOB(year, month, day int) time.Time {
    dob := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
    return dob
}

Output:

Age is 8