diff --git a/calendar/calendar.go b/calendar/calendar.go index 539921f5..08fc33ee 100644 --- a/calendar/calendar.go +++ b/calendar/calendar.go @@ -97,3 +97,51 @@ func (d *HoursMinutesSeconds) UnmarshalString(str string) error { return nil } + +// Diff_dates - вычисляет разницу между двумя датами +func Diff_dates(a, b time.Time) (year, month, day, hour, min, sec int) { + if a.Location() != b.Location() { + b = b.In(a.Location()) + } + if a.After(b) { + a, b = b, a + } + y1, M1, d1 := a.Date() + y2, M2, d2 := b.Date() + + h1, m1, s1 := a.Clock() + h2, m2, s2 := b.Clock() + + year = int(y2 - y1) + month = int(M2 - M1) + day = int(d2 - d1) + hour = int(h2 - h1) + min = int(m2 - m1) + sec = int(s2 - s1) + + // Normalize negative values + if sec < 0 { + sec += 60 + min-- + } + if min < 0 { + min += 60 + hour-- + } + if hour < 0 { + hour += 24 + day-- + } + if day < 0 { + // days in month: + t := time.Date(y1, M1, 32, 0, 0, 0, 0, time.UTC) + day += 32 - t.Day() + month-- + } + if month < 0 { + month += 12 + year-- + } + + return +} diff --git a/calendar/calendar_test.go b/calendar/calendar_test.go index 98ab2b97..8f04db25 100644 --- a/calendar/calendar_test.go +++ b/calendar/calendar_test.go @@ -32,3 +32,13 @@ func TestHoursMinutesSeconds_UnmarshalByte(t *testing.T) { t.Error("TestHoursMinutesSeconds_UnmarshalByte error") } } + +func TestDiff_dates(t *testing.T) { + + Date1 := time.Date(2023, 03, 19, 0, 0, 0, 0, constants.Loc) + Date2 := time.Date(2023, 03, 20, 0, 0, 0, 0, constants.Loc) + _, _, days, _, _, _ := Diff_dates(Date1, Date2) + if days != 1 { + t.Error("TestDiff_dates error") + } +}