Created
October 17, 2019 08:28
-
-
Save mfirhas/be4ac76526f6642fbf605156affe7dd5 to your computer and use it in GitHub Desktop.
get diff between 2 time in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func diff(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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
courtesy: https://golangr.com/difference-between-two-dates/