-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculate.go
64 lines (49 loc) · 1.46 KB
/
calculate.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package age
import (
"time"
leapYear "github.com/theTardigrade/golang-leapYear"
)
const (
calculateLeapYearDay = 60
)
func calculate(startTime, endTime time.Time) int {
startYear := startTime.Year()
endYear := endTime.Year()
age := endYear - startYear
startYearIsLeapYear := leapYear.Is(startYear)
endYearIsLeapYear := leapYear.Is(endYear)
startYearDay := startTime.YearDay()
endYearDay := endTime.YearDay()
if startYearIsLeapYear && !endYearIsLeapYear && startYearDay >= calculateLeapYearDay {
startYearDay--
} else if endYearIsLeapYear && !startYearIsLeapYear && endYearDay >= calculateLeapYearDay {
startYearDay++
}
if endYearDay < startYearDay {
age--
}
return age
}
// Calculate returns an integer-value age based on the duration
// between the two times that are given as arguments.
func Calculate(startTime, endTime time.Time) int {
switch endLocation := endTime.Location(); endLocation {
case time.UTC, nil:
startTime = startTime.UTC()
default:
startTime = startTime.In(endLocation)
}
return calculate(startTime, endTime)
}
// Calculate returns an integer-value age based on the duration
// between the given time and the present time.
func CalculateToNow(givenTime time.Time) int {
presentTime := time.Now().UTC()
switch givenLocation := givenTime.Location(); givenLocation {
case time.UTC, nil:
presentTime = presentTime.UTC()
default:
presentTime = presentTime.In(givenLocation)
}
return calculate(givenTime, presentTime)
}