Skip to content

Instantly share code, notes, and snippets.

@VinGarcia
Last active April 21, 2021 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VinGarcia/a6c72b523e7568355d5a6b345813f54f to your computer and use it in GitHub Desktop.
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 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