在 Go 语言中,时间包提供了确定和查看时间的功能。 Go 语言中的Date()函数用于在指定位置的适当时区中查找日期时间,该时间相当于yyyy-mm-dd hh:mm:ss + nsec 纳秒。而且,这个函数是在time包下定义的。在这里,您需要导入“time”包才能使用这些功能。
句法:
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
在这里,“loc”指向位置。
返回值:它返回转换中两个关联区域之一中正确的时间,但不保证返回哪一个。如果给定的“loc”为零,它会返回恐慌。
注意:这里的月、日、小时、分钟、秒和纳秒的值可以大于正常范围,但它们会在转换过程中自动归一化。例如,如果日期是 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
此处,天、小时和分钟的值范围在正常范围之外,但它们在转换过程中被标准化。