From 9491b72b8dc44afb8ee96b64c69c9b7912fbb885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Sat, 30 Mar 2024 03:01:55 +0100 Subject: [PATCH] v0.0.424 timeext.SubtractYears --- goextVersion.go | 4 ++-- timeext/time.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/goextVersion.go b/goextVersion.go index 2e89a07..3522582 100644 --- a/goextVersion.go +++ b/goextVersion.go @@ -1,5 +1,5 @@ package goext -const GoextVersion = "0.0.423" +const GoextVersion = "0.0.424" -const GoextVersionTimestamp = "2024-03-24T15:25:52+0100" +const GoextVersionTimestamp = "2024-03-30T03:01:55+0100" diff --git a/timeext/time.go b/timeext/time.go index 34b2a70..4af8ac1 100644 --- a/timeext/time.go +++ b/timeext/time.go @@ -146,3 +146,37 @@ func UnixFloatSeconds(v float64) time.Time { func FloorTime(t time.Time) time.Time { return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) } + +func SubtractYears(t time.Time, yearCount float64, tz *time.Location) time.Time { + t = t.In(tz) + + if yearCount < 0 { + return AddYears(t, -yearCount, tz) + } + + intCount, floatCount := math.Modf(yearCount) + + t.AddDate(-int(intCount), 0, 0) + + t0 := TimeToYearStart(t, tz) + t1 := TimeToYearEnd(t, tz) + + return t.Add(time.Duration(float64(t1.Sub(t0)) * floatCount * -1)) +} + +func AddYears(t time.Time, yearCount float64, tz *time.Location) time.Time { + t = t.In(tz) + + if yearCount < 0 { + return SubtractYears(t, -yearCount, tz) + } + + intCount, floatCount := math.Modf(yearCount) + + t.AddDate(int(intCount), 0, 0) + + t0 := TimeToYearStart(t, tz) + t1 := TimeToYearEnd(t, tz) + + return t.Add(time.Duration(float64(t1.Sub(t0)) * floatCount)) +}