1
0
mirror of https://github.com/ManyakRus/starter.git synced 2025-11-23 22:45:11 +02:00

сделал Diff_dates()

This commit is contained in:
Nikitin Aleksandr
2025-05-20 15:43:12 +03:00
parent f897ec97ef
commit e6fddc2907
2 changed files with 58 additions and 0 deletions

View File

@@ -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
}

View File

@@ -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")
}
}