Add days to date in Go

I'm trying to add a number of days (actually a number of weeks) to an existing date in Go. I have tried myDate.Add(time.Hour * 24 * 7 * weeksToAdd)

But I get an error when I try to build: invalid operation: time.Hour * startAdd (mismatched types time.Duration and float64)

So weeksToAdd is currently a float64, but I can change it to an int or whatever. Changing it to an int only changed my error to say that int and Duration can't be multiplied.

How do I add days to a date?


Use Time.AddDate():

myDate.AddDate(0, 0, 7 * weeksToAdd)

You need to convert weeksToAdd into a time.Duration:

myDate.Add(time.Hour * 24 * 7 * time.Duration(weeksToAdd))

In Go, type aliases cannot be used interchangeably even though time.Duration is technically an int64.

Also, here, even though the numeric constants 24 and 7 are not explicitly typed, they can still be used as-is, see https://blog.golang.org/constants for an in-depth explanation.

See http://play.golang.org/p/86TFFlixWj for a running example.

As mentioned in comments and another answer, the use of time.AddDate() is preferable to time.Add() when working on duration superior to 24 hours, since time.Duration basically represents nanoseconds. When working with days, weeks, months and years, a lot of care has to be taken because of things such as daylight saving times, leap years, and maybe potentially leap seconds.

The documentation for time.Duration type and the associated constants representing units emphasize this issue (https://golang.org/pkg/time/#Duration):

There is no definition for units of Day or larger to avoid confusion across daylight savings time zone transitions.