How To Add Day To Date In Go (Golang)
Working with times and dates in Go (Golang) is extremely easy. This is because Go offers a handy time.Time package straight out of the standard library. This allows us to work easily with times and dates without having to install third party dependencies.
If you have a look at the official documentation for the time.Time package you will see the following
type Time struct {
// contains filtered or unexported fields
}
A Time represents an instant in time with nanosecond precision.
Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time.
You can also see some useful functions with time.Time, such as time.AddDate()
func (t Time) AddDate(years int, months int, days int) Time
AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.
This is the exact function we need to add days to a date (time.Time) in Go (Golang).
How to add a day to a date in Go (Golang)
In order to add a specific number of days to a date in Go you can use the time.AddDate function as follows:
package main
import (
"log"
"time"
)
func main() {
t1, err := time.Parse("2006-01-02", "2023-05-27")
if err != nil {
log.Fatal(err)
}
log.Println(t1.Format("02 Jan 2006"))
t2 := t1.AddDate(0, 0, 30)
log.Println(t2.Format("02 Jan 2006"))
}
The expected output is as follows:
2009/11/10 23:00:00 27 May 2023
2009/11/10 23:00:00 26 Jun 2023
You can also run this Go example yourself via the Go Playground https://go.dev/play/p/3KJ5HxqkoHC
How to add a month to a date in Go (Golang)
The same applies if you want to add a month to a pre defined date (time.Time) in Go (Golang). Just use the time.AddDate function and that should work as expected.
Please see the example as follows:
package main
import (
"log"
"time"
)
func main() {
t1, err := time.Parse("2006-01-02", "2023-05-27")
if err != nil {
log.Fatal(err)
}
log.Println(t1.Format("02 Jan 2006"))
t2 := t1.AddDate(0, 2, 0)
log.Println(t2.Format("02 Jan 2006"))
}
The expected output is as follows:
2009/11/10 23:00:00 27 May 2023
2009/11/10 23:00:00 27 Jul 2023