Epoch {.en}
时代 {.zh}
::: {.en} A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Go. :::
::: {.zh}
程序中的一个常见要求是获取自[Unix纪元](http://en.wikipedia.org/wiki/Unix_time)以来的秒数,毫秒数或纳秒数。这是如何在Go中完成的。
:::
package mainimport "fmt"import "time"func main() {
::: {.en}
Use time.Now with Unix or UnixNano to get
elapsed time since the Unix epoch in seconds or
nanoseconds, respectively.
:::
::: {.zh}
使用Unix或UnixNano的’time.Now`分别来自Unix纪元以来的getelapsed时间,分别为秒或纳秒。
:::
now := time.Now()secs := now.Unix()nanos := now.UnixNano()fmt.Println(now)
::: {.en}
Note that there is no UnixMillis, so to get the
milliseconds since epoch you’ll need to manually
divide from nanoseconds.
:::
::: {.zh}
请注意,没有UnixMillis,所以要从epoch获得它们,你需要手动从纳秒开始。
:::
millis := nanos / 1000000fmt.Println(secs)fmt.Println(millis)fmt.Println(nanos)
::: {.en}
You can also convert integer seconds or nanoseconds
since the epoch into the corresponding time.
:::
::: {.zh}
您也可以将整数秒或纳秒从历元转换为相应的“时间”。
:::
fmt.Println(time.Unix(secs, 0))fmt.Println(time.Unix(0, nanos))}
$ go run epoch.go2012-10-31 16:13:58.292387 +0000 UTC1351700038135170003829213517000382923870002012-10-31 16:13:58 +0000 UTC2012-10-31 16:13:58.292387 +0000 UTC
::: {.en} Next we’ll look at another time-related task: time parsing and formatting. :::
::: {.zh}
接下来我们将看另一个与时间相关的任务:timeparsing和format。
:::
