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?
AddDate() is preferable to time. Add() when working on duration superior to 24 hours, since time. Duration basically represents nanoseconds.
For example, a 4-digit year might be represented by %Y . In Go, though, these parts of a date or time are represented by characters that represent a specific date. To include a 4-digit year in a Go date format, you would actually include 2006 in the string itself.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With