Created
May 12, 2016 03:03
-
-
Save jostyee/220ca0bab71072ad3b18e20b7f924084 to your computer and use it in GitHub Desktop.
Calculate Days Between Dates
This file contains 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
// original post: https://groups.google.com/d/msg/golang-nuts/O2NaRAH94GI/eXrvZtsTCQAJ | |
package days | |
import ( | |
"fmt" | |
"time" | |
) | |
func lastDayOfYear(t time.Time) time.Time { | |
return time.Date(t.Year(), 12, 31, 0, 0, 0, 0, t.Location()) | |
} | |
func firstDayOfNextYear(t time.Time) time.Time { | |
return time.Date(t.Year()+1, 1, 1, 0, 0, 0, 0, t.Location()) | |
} | |
// a - b in days | |
func daysDiff(a, b time.Time) (days int) { | |
cur := b | |
for cur.Year() < a.Year() { | |
// add 1 to count the last day of the year too. | |
days += lastDayOfYear(cur).YearDay() - cur.YearDay() + 1 | |
cur = firstDayOfNextYear(cur) | |
} | |
days += a.YearDay() - cur.YearDay() | |
if b.AddDate(0, 0, days).After(a) { | |
days -= 1 | |
} | |
return days | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment