Time {.en}

时间 {.zh}

::: {.en} Go offers extensive support for times and durations; here are some examples. :::

::: {.zh}

Go为时间和持续时间提供了广泛的支持;这里有一些例子。

:::

  1. package main
  2. import "fmt"
  3. import "time"
  4. func main() {
  5. p := fmt.Println

::: {.en} We’ll start by getting the current time. :::

::: {.zh}

我们先从获取当前时间开始。

:::

  1. now := time.Now()
  2. p(now)

::: {.en} You can build a time struct by providing the year, month, day, etc. Times are always associated with a Location, i.e. time zone. :::

::: {.zh}

您可以通过提供它们,月,日等来构建“时间”结构。时间总是与“位置”相关联,即时区。

:::

  1. then := time.Date(
  2. 2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
  3. p(then)

::: {.en} You can extract the various components of the time value as expected. :::

::: {.zh}

您可以按预期提取时间值的各个组件。

:::

  1. p(then.Year())
  2. p(then.Month())
  3. p(then.Day())
  4. p(then.Hour())
  5. p(then.Minute())
  6. p(then.Second())
  7. p(then.Nanosecond())
  8. p(then.Location())

::: {.en} The Monday-Sunday Weekday is also available. :::

::: {.zh}

周一至周日的“工作日”也可用。

:::

  1. p(then.Weekday())

::: {.en} These methods compare two times, testing if the first occurs before, after, or at the same time as the second, respectively. :::

::: {.zh}

这些方法比较两次,分别测试第一次发生在第二次之前,之后或同一时间。

:::

  1. p(then.Before(now))
  2. p(then.After(now))
  3. p(then.Equal(now))

::: {.en} The Sub methods returns a Duration representing the interval between two times. :::

::: {.zh}

Sub方法返回一个’Duration`表示两次之间的间隔。

:::

  1. diff := now.Sub(then)
  2. p(diff)

::: {.en} We can compute the length of the duration in various units. :::

::: {.zh}

我们可以计算持续时间不变单位的长度。

:::

  1. p(diff.Hours())
  2. p(diff.Minutes())
  3. p(diff.Seconds())
  4. p(diff.Nanoseconds())

::: {.en} You can use Add to advance a time by a given duration, or with a - to move backwards by a duration. :::

::: {.zh}

您可以使用“添加”来通过完成来提前一段时间,或者使用“-”通过添加来向后移动。

:::

  1. p(then.Add(diff))
  2. p(then.Add(-diff))
  3. }
  1. $ go run time.go
  2. 2012-10-31 15:50:13.793654 +0000 UTC
  3. 2009-11-17 20:34:58.651387237 +0000 UTC
  4. 2009
  5. November
  6. 17
  7. 20
  8. 34
  9. 58
  10. 651387237
  11. UTC
  12. Tuesday
  13. true
  14. false
  15. false
  16. 25891h15m15.142266763s
  17. 25891.25420618521
  18. 1.5534752523711128e+06
  19. 9.320851514226677e+07
  20. 93208515142266763
  21. 2012-10-31 15:50:13.793654 +0000 UTC
  22. 2006-12-05 01:19:43.509120474 +0000 UTC

::: {.en} Next we’ll look at the related idea of time relative to the Unix epoch. :::

::: {.zh}

接下来我们将看看相对于Unix时代的相关时间概念。

:::