-
Notifications
You must be signed in to change notification settings - Fork 18
/
age.go
49 lines (42 loc) · 1.32 KB
/
age.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Package age allows for easy calculation of the age of an entity, provided with the date of birth of that entity.
package age
import "time"
// AgeAt gets the age of an entity at a certain time.
func AgeAt(birthDate time.Time, now time.Time) int {
// Get the year number change since the player's birth.
years := now.Year() - birthDate.Year()
// If the date is before the date of birth, then not that many years have elapsed.
birthDay := getAdjustedBirthDay(birthDate, now)
if now.YearDay() < birthDay {
years -= 1
}
return years
}
// Age is shorthand for AgeAt(birthDate, time.Now()), and carries the same usage and limitations.
func Age(birthDate time.Time) int {
return AgeAt(birthDate, time.Now())
}
// Gets the adjusted date of birth to work around leap year differences.
func getAdjustedBirthDay(birthDate time.Time, now time.Time) int {
birthDay := birthDate.YearDay()
currentDay := now.YearDay()
if isLeap(birthDate) && !isLeap(now) && birthDay >= 60 {
return birthDay - 1
}
if isLeap(now) && !isLeap(birthDate) && currentDay >= 60 {
return birthDay + 1
}
return birthDay
}
// Works out if a time.Time is in a leap year.
func isLeap(date time.Time) bool {
year := date.Year()
if year%400 == 0 {
return true
} else if year%100 == 0 {
return false
} else if year%4 == 0 {
return true
}
return false
}