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中完成的。

:::

  1. package main
  2. import "fmt"
  3. import "time"
  4. func main() {

::: {.en} Use time.Now with Unix or UnixNano to get elapsed time since the Unix epoch in seconds or nanoseconds, respectively. :::

::: {.zh}

使用UnixUnixNano的’time.Now`分别来自Unix纪元以来的getelapsed时间,分别为秒或纳秒。

:::

  1. now := time.Now()
  2. secs := now.Unix()
  3. nanos := now.UnixNano()
  4. 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获得它们,你需要手动从纳秒开始。

:::

  1. millis := nanos / 1000000
  2. fmt.Println(secs)
  3. fmt.Println(millis)
  4. fmt.Println(nanos)

::: {.en} You can also convert integer seconds or nanoseconds since the epoch into the corresponding time. :::

::: {.zh}

您也可以将整数秒或纳秒从历元转换为相应的“时间”。

:::

  1. fmt.Println(time.Unix(secs, 0))
  2. fmt.Println(time.Unix(0, nanos))
  3. }
  1. $ go run epoch.go
  2. 2012-10-31 16:13:58.292387 +0000 UTC
  3. 1351700038
  4. 1351700038292
  5. 1351700038292387000
  6. 2012-10-31 16:13:58 +0000 UTC
  7. 2012-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。

:::