Skip to content

Instantly share code, notes, and snippets.

@mfirhas
Created October 17, 2019 08:28
Show Gist options
  • Save mfirhas/be4ac76526f6642fbf605156affe7dd5 to your computer and use it in GitHub Desktop.
Save mfirhas/be4ac76526f6642fbf605156affe7dd5 to your computer and use it in GitHub Desktop.
get diff between 2 time in go
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
}
@mfirhas
Copy link
Author

mfirhas commented Oct 17, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment