time.Time.AddDate() Function in Golang with Examples
Last Updated :
19 Apr, 2020
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:
package main
import "fmt"
import "time"
func main() {
Time := time .Date(2018, 6, 4, 0, 0, 0, 0, time .UTC)
t1 := Time.AddDate(1, 2, 5)
t2 := Time.AddDate(5, -2, 9)
t3 := Time.AddDate(0, 3, -3)
t4 := Time.AddDate(1, 0, 0)
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:
package main
import "fmt"
import "time"
func main() {
Time := time .Date(2020, 15, 34, 0, 0, 0, 0, time .UTC)
t1 := Time.AddDate(3, 13, 35)
t2 := Time.AddDate(2, -24, 29)
t3 := Time.AddDate(4, 32, -31)
t4 := Time.AddDate(5, 10, -11)
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.
Share your thoughts in the comments
Please Login to comment...