2024-07-04 16:24:49 +02:00
|
|
|
package timeext
|
|
|
|
|
|
|
|
import "time"
|
|
|
|
|
2024-08-26 14:35:49 +02:00
|
|
|
// YearDifference calculates the difference between two timestamps in years.
|
|
|
|
// = t1 - t2
|
|
|
|
// returns a float value
|
2024-07-04 16:24:49 +02:00
|
|
|
func YearDifference(t1 time.Time, t2 time.Time, tz *time.Location) float64 {
|
|
|
|
|
|
|
|
yDelta := float64(t1.Year() - t2.Year())
|
|
|
|
|
|
|
|
processT1 := float64(t1.Sub(TimeToYearStart(t1, tz))) / float64(TimeToYearEnd(t1, tz).Sub(TimeToYearStart(t1, tz)))
|
|
|
|
processT2 := float64(t2.Sub(TimeToYearStart(t2, tz))) / float64(TimeToYearEnd(t2, tz).Sub(TimeToYearStart(t2, tz)))
|
|
|
|
|
|
|
|
return yDelta + (processT1 - processT2)
|
|
|
|
}
|
2024-08-26 14:35:49 +02:00
|
|
|
|
|
|
|
// MonthDifference calculates the difference between two timestamps in months.
|
|
|
|
// = t1 - t2
|
|
|
|
// returns a float value
|
|
|
|
func MonthDifference(t1 time.Time, t2 time.Time) float64 {
|
|
|
|
|
|
|
|
yDelta := float64(t1.Year() - t2.Year())
|
|
|
|
mDelta := float64(t1.Month() - t2.Month())
|
|
|
|
|
|
|
|
dDelta := float64(0)
|
|
|
|
|
|
|
|
t1MonthDays := DaysInMonth(t1)
|
|
|
|
t2MonthDays := DaysInMonth(t2)
|
|
|
|
|
|
|
|
if t2.Year() > t1.Year() || (t2.Year() == t1.Year() && t2.Month() > t1.Month()) {
|
|
|
|
dDelta -= 1
|
|
|
|
dDelta += float64(t1MonthDays-t1.Day()) / float64(t1MonthDays)
|
|
|
|
dDelta += float64(t2.Day()) / float64(t2MonthDays)
|
|
|
|
} else if t2.Year() < t1.Year() || (t2.Year() == t1.Year() && t2.Month() < t1.Month()) {
|
|
|
|
dDelta -= 1
|
|
|
|
dDelta += float64(t1.Day()) / float64(t1MonthDays)
|
|
|
|
dDelta += float64(t2MonthDays-t2.Day()) / float64(t2MonthDays)
|
|
|
|
} else {
|
|
|
|
dDelta += float64(t1.Day()-t2.Day()) / float64(t1MonthDays)
|
|
|
|
}
|
|
|
|
|
|
|
|
return yDelta*12 + mDelta + dDelta
|
|
|
|
}
|