Menu Close

Go – Add years, months, days to current date in Go

Here, we are going to learn about how to add years, months, days to current date in Go. We will learn it by example and program.

AddDate() method of time structure will be used to add years, months and days to current date.

Function prototype:

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

years: Years to be added

months: Months to be added

days: Days to be added

Return value:

AddDate() function in time package returns the time corresponding to adding the given number of years, months, and days to t.

Example:

Date: February 1, 2019

Apply: AddDate(1, 2, 3)

Here, Going to add 1 year, 2 months and 3 days in the given date.

Final date: April 4, 2020

Program:

package main

import (

  "fmt"
  "time"
)

func main() {


  curr_date := time.Date(2010, 1, 1, 0, 0, 0, 0, time.UTC)

  oneDayLater := curr_date.AddDate(0, 0, 1)

  oneMonthLater := curr_date.AddDate(0, 1, 0)

  oneYearLater := curr_date.AddDate(1, 0, 0)

  oneYearBack := curr_date.AddDate(-1, 0, 0)



  fmt.Println("Current date: ", curr_date)

  fmt.Println("oneDayLater: ", oneDayLater)

  fmt.Println("oneMonthLater: ", oneMonthLater)

  fmt.Println("oneYearLater: ", oneYearLater)

  fmt.Println("oneYearBack: ", oneYearBack)

}

Output:

$ go run sample.go

Current date: 2010-01-01 00:00:00 +0000 UTC

oneDayLater: 2010-01-02 00:00:00 +0000 UTC

oneMonthLater: 2010-02-01 00:00:00 +0000 UTC

oneYearLater: 2011-01-01 00:00:00 +0000 UTC

oneYearBack: 2009-01-01 00:00:00 +0000 UTC

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, time