Golang time.Unix()函数及示例
在Go语言中,time包提供了确定和查看时间的功能。在Go语言中,Unix()函数用于生成与UTC中1970年1月1日规定的Unix时间相关联的本地时间。此外,该函数是在time包下定义的。在这里,您需要导入“time”包才能使用这些函数。
语法:
func Unix(sec int64, nsec int64) Time
在这里,“sec”是类型为int64的秒数,“nsec”也是类型为int64的纳秒数。
注意: 允许“nsec”超出范围[0,999999999]是合理的。但是,并不是每个“sec”值都有等价的时间值,其中一个类似值是1<<63-1,即为int64值最大的值。
返回值: 它返回与UTC中1970年1月1日规定的Unix时间相等的本地时间。
示例1:
// Golang program to illustrate the usage of
// time.Unix() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Calling Unix method with 275 seconds
// and zero nanoseconds and also
// printing output
fmt.Println(time.Unix(275, 0).UTC())
// Calling Unix method with 0 seconds and
// 566 nanoseconds and also printing
// output
fmt.Println(time.Unix(0, 566).UTC())
// Calling Unix method with 456 seconds and
// -67 nanoseconds and also printing
// output
fmt.Println(time.Unix(456, -67).UTC())
}
输出:
1970年1月1日00:04:35 +0000 UTC
1970年1月1日00:00:00.000000566 +0000 UTC
1970年1月1日00:07:35.999999933 +0000 UTC
示例2:
// Golang program to illustrate the usage of
// time.Unix() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Calling Unix method with 2e1 seconds
// and zero nanoseconds and also
// printing output
fmt.Println(time.Unix(2e1, 0).UTC())
// Calling Unix method with 0 seconds and
// 1e13 nanoseconds and also printing
// output
fmt.Println(time.Unix(0, 1e13).UTC())
// Calling Unix method with 1e1 seconds and
// -1e15 nanoseconds and also printing
// output
fmt.Println(time.Unix(1e1, -1e15).UTC())
}
输出:
1970年1月1日00:00:20 +0000 UTC
1970年1月1日02:46:40 +0000 UTC
1969年12月20日10:13:30 +0000 UTC
在这里,上面代码中Unix()方法的参数具有包含“e”的值,这些值在转换过程中被转换为常规范围。