Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add days to date in Go

Tags:

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?

like image 309
Ben Walker Avatar asked Oct 07 '15 16:10

Ben Walker


People also ask

How do you add days to a date in go?

AddDate() is preferable to time. Add() when working on duration superior to 24 hours, since time. Duration basically represents nanoseconds.

How do you store dates in go?

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.


2 Answers

Use Time.AddDate():

myDate.AddDate(0, 0, 7 * weeksToAdd)
like image 56
kostix Avatar answered Oct 18 '22 11:10

kostix


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.

like image 22
SirDarius Avatar answered Oct 18 '22 13:10

SirDarius