在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的Time.AddDate()函數用於檢查時間,等效於將給定的“t”添加指定的年數,月數和天數。例如,如果該方法的參數為(-2,4,5),且指定的t為2018年2月3日,則輸出將為2016年6月8日。如此處的Date方法,如果月份,天的範圍也是如此或年份超出正常範圍,則其會自動轉換為正常範圍。此外,此函數在時間包下定義。在這裏,您需要導入“time”軟件包才能使用這些函數。
用法:
func (t Time) AddDate(years int, months int, days int) Time
在這裏,“t”是規定的時間。
返回值:它返回將陳述的t加到陳述的年數,月數和天數中的結果。
範例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)
}
輸出:
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
此處,返回的輸出采用上述UTC格式。
範例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)
}
輸出:
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
此處,使用的範圍超出了通常範圍,但在轉換時將其標準化。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 time.Time.AddDate() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。