Open In App

time.Time.AddDate() Function in Golang with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

In Go language, time packages supplies functionality for determining as well as viewing time. The Time.AddDate() function in Go language is used to check the time which is equivalent to adding the stated number of years, months, and days to the given “t”.
For example, if the parameters of the method are like (-2, 4, 5) and the stated t is February 3, 2018 then the output will be June 8, 2016. Like Date method here also if the range of months, days or years are outside the normal range then its automatically converted to normalized range. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions.

Syntax:

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

Here, “t” is the stated time.

Return Value: It returns the result of adding stated t to the stated number of years, months, and days.

Example 1:




// Golang program to illustrate the usage of
// Time.AddDate() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Declaring Time in UTC
    Time := time.Date(2018, 6, 4, 0, 0, 0, 0, time.UTC)
  
    // Calling AddDate method with all
    // its parameters
    t1 := Time.AddDate(1, 2, 5)
    t2 := Time.AddDate(5, -2, 9)
    t3 := Time.AddDate(0, 3, -3)
    t4 := Time.AddDate(1, 0, 0)
  
    // Prints output
    fmt.Printf("%v\n", Time)
    fmt.Printf("%v\n", t1)
    fmt.Printf("%v\n", t2)
    fmt.Printf("%v\n", t3)
    fmt.Printf("%v\n", t4)
}


Output:

2018-06-04 00:00:00 +0000 UTC
2019-08-09 00:00:00 +0000 UTC
2023-04-13 00:00:00 +0000 UTC
2018-09-01 00:00:00 +0000 UTC
2019-06-04 00:00:00 +0000 UTC

Here, the output returned is in UTC as defined above.

Example 2:




// Golang program to illustrate the usage of
// Time.AddDate() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Declaring Time in UTC
    Time := time.Date(2020, 15, 34, 0, 0, 0, 0, time.UTC)
  
    // Calling AddDate method with all
    // its parameters
    t1 := Time.AddDate(3, 13, 35)
    t2 := Time.AddDate(2, -24, 29)
    t3 := Time.AddDate(4, 32, -31)
    t4 := Time.AddDate(5, 10, -11)
  
    // Prints output
    fmt.Printf("%v\n", Time)
    fmt.Printf("%v\n", t1)
    fmt.Printf("%v\n", t2)
    fmt.Printf("%v\n", t3)
    fmt.Printf("%v\n", t4)
}


Output:

2021-04-03 00:00:00 +0000 UTC
2025-06-07 00:00:00 +0000 UTC
2021-05-02 00:00:00 +0000 UTC
2027-11-02 00:00:00 +0000 UTC
2027-01-23 00:00:00 +0000 UTC

Here, the range used is outside the usual range but they are normalized while converted.



Last Updated : 19 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads