Ben Walker
Ben Walker

Reputation: 2137

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?

Upvotes: 63

Views: 88839

Answers (3)

SirDarius
SirDarius

Reputation: 42959

You need to convert weeksToAdd into a time.Duration:

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

In Go, defined types cannot be used interchangeably even though time.Duration is technically defined as 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.

Upvotes: 30

чистов_n
чистов_n

Reputation: 107

As an adding to @kostix answer.

myDate not changes when AddDate called. AddDate returns new date.

So, to change myDate you need to write:

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

Upvotes: 0

kostix
kostix

Reputation: 55553

Use Time.AddDate():

func (t Time) AddDate(years int, months int, days int) Time

Example:

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

Upvotes: 125

Related Questions