在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的Date()函數用於在指定位置的正確時區中找到與yyyy-mm-dd hh:mm:ss + nsec納秒等效的日期時間。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。
用法:
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
在此,“loc”指向該位置。
返回值:它會在轉換的兩個關聯區域之一中返回適當的時間,但不能保證會返回哪個時間。如果給定的“loc”為nil,它將返回恐慌。
注意:此處,月,日,小時,分鍾,秒和秒的值可以大於正常範圍,但在轉換過程中會自動將其標準化。例如,如果日期為4月34日,則將其轉換為5月1日。
範例1:
// Golang program to illustrate the usage of
// time.Date() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Calling Date() method
// with all its parameters
tm := time.Date(2020, time.April,
11, 21, 34, 01, 0, time.UTC)
// Using Local() for location and printing
// the stated time and date in UTC
fmt.Printf("%s", tm.Local())
}
輸出:
2020-04-11 21:34:01 +0000 UTC
範例2:
// Golang program to illustrate the usage of
// time.Date() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Calling Date() method
// with all its parameters
tm := time.Date(2020, time.April,
34, 25, 72, 01, 0, time.UTC)
// Using Local() for location and printing
// the stated time and date in UTC
fmt.Printf("%s", tm.Local())
}
輸出:
2020-05-05 02:12:01 +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.Date() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。