How to add/subtract days, months or years to a date in Go Language
Hello everyone, In this tutorial, we will learn how to add/subtract days, months or years to a date in Go Language.
The time package in Go language provides AddDate() function which is used to add/subtract years, months and days to time t.
The signature of the AddDate method is:
func (t Time) AddDate(years int, months int, days int) Time
Example 1: Go Program to add/subtract days.
package main
import ( "fmt" "time")
func main() {
//Current date and time dt1 := time.Now() fmt.Println("Current date and time : ", dt1)
//Adding 3 days dt2 := dt1.AddDate(0, 0, 3) fmt.Println("After three days: ", dt2)
//Subtract 400 days dt3 := dt1.AddDate(0, 0, -400) fmt.Println("Before 400 days: ", dt3)}
Output:
Example 2: Go Program to add/subtract months.
package main
import ( "fmt" "time")
func main() {
//Current date and time dt1 := time.Now() fmt.Println("Current date and time : ", dt1)
//Adding 3 months dt2 := dt1.AddDate(0, 3, 0) fmt.Println("After three months: ", dt2)
//Subtract 9 months dt3 := dt1.AddDate(0, -9, 0) fmt.Println("Before 9 months: ", dt3)}
Output:
Example 3: Go Program to add/subtract years.
package main
import ( "fmt" "time")
func main() {
//Current date and time dt1 := time.Now() fmt.Println("Current date and time : ", dt1)
//Adding 2 years dt2 := dt1.AddDate(2, 0, 0) fmt.Println("After two years: ", dt2)
//Subtract 7 years dt3 := dt1.AddDate(-7, 0, 0) fmt.Println("Before 7 years: ", dt3)}