Last active
April 21, 2021 19:05
-
-
Save VinGarcia/a6c72b523e7568355d5a6b345813f54f to your computer and use it in GitHub Desktop.
Implements an AddDate for Golang that works more like humans calculate dates (see issue in comment)
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
// This function had to be created because of an | |
// issue on the time.Time#AddDate() function: | |
// | |
// - https://github.com/golang/go/issues/31145 | |
// | |
// where adding a month to Jan 30 would not get Feb 28 | |
func addDate(date time.Time, y, m, d int) time.Time { | |
expectedMonth := (date.Month()+time.Month(m)-1)%12 + 1 | |
date = date.AddDate(y, m, 0) | |
if date.Month() == expectedMonth { | |
return date.AddDate(0, 0, d) | |
} | |
return date.AddDate(0, 0, d-date.Day()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment