程序中的一个常见要求是获取自unix纪元以来的秒数,毫秒或纳秒数。这里是如何在go编程中做。
使用unix或unixnano的time.now
,分别以秒或纳秒为单位获得自unix纪元起的耗用时间。
注意,没有unixmillis
,所以要获取从纪元开始的毫秒数,需要手动除以纳秒。
还可以将整数秒或纳秒从历元转换为相应的时间。
具体的 epoch
用法,可参考示例中的代码 -
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html
json.go
的完整代码如下所示 -
package main
import "fmt"
import "time"
func main() {
// use `time.now` with `unix` or `unixnano` to get
// elapsed time since the unix epoch in seconds or
// nanoseconds, respectively.
now := time.now()
secs := now.unix()
nanos := now.unixnano()
fmt.println(now)
// note that there is no `unixmillis`, so to get the
// milliseconds since epoch you'll need to manually
// divide from nanoseconds.
millis := nanos / 1000000
fmt.println(secs)
fmt.println(millis)
fmt.println(nanos)
// you can also convert integer seconds or nanoseconds
// since the epoch into the corresponding `time`.
fmt.println(time.unix(secs, 0))
fmt.println(time.unix(0, nanos))
}
执行上面代码,将得到以下输出结果 -
f:\worksp\golang>go run epoch.go
2017-01-22 09:16:32.2002635 +0800 cst
1485047792
1485047792200
1485047792200263500
2017-01-22 09:16:32 +0800 cst
2017-01-22 09:16:32.2002635 +0800 cst