Time {.en}
时间 {.zh}
::: {.en} Go offers extensive support for times and durations; here are some examples. :::
::: {.zh}
Go为时间和持续时间提供了广泛的支持;这里有一些例子。
:::
package main
import "fmt"
import "time"
func main() {
p := fmt.Println
::: {.en} We’ll start by getting the current time. :::
::: {.zh}
我们先从获取当前时间开始。
:::
now := time.Now()
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}
您可以通过提供它们,月,日等来构建“时间”结构。时间总是与“位置”相关联,即时区。
:::
then := time.Date(
2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
p(then)
::: {.en} You can extract the various components of the time value as expected. :::
::: {.zh}
您可以按预期提取时间值的各个组件。
:::
p(then.Year())
p(then.Month())
p(then.Day())
p(then.Hour())
p(then.Minute())
p(then.Second())
p(then.Nanosecond())
p(then.Location())
::: {.en}
The Monday-Sunday Weekday
is also available.
:::
::: {.zh}
周一至周日的“工作日”也可用。
:::
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}
这些方法比较两次,分别测试第一次发生在第二次之前,之后或同一时间。
:::
p(then.Before(now))
p(then.After(now))
p(then.Equal(now))
::: {.en}
The Sub
methods returns a Duration
representing
the interval between two times.
:::
::: {.zh}
Sub
方法返回一个’Duration`表示两次之间的间隔。
:::
diff := now.Sub(then)
p(diff)
::: {.en} We can compute the length of the duration in various units. :::
::: {.zh}
我们可以计算持续时间不变单位的长度。
:::
p(diff.Hours())
p(diff.Minutes())
p(diff.Seconds())
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}
您可以使用“添加”来通过完成来提前一段时间,或者使用“-”通过添加来向后移动。
:::
p(then.Add(diff))
p(then.Add(-diff))
}
$ go run time.go
2012-10-31 15:50:13.793654 +0000 UTC
2009-11-17 20:34:58.651387237 +0000 UTC
2009
November
17
20
34
58
651387237
UTC
Tuesday
true
false
false
25891h15m15.142266763s
25891.25420618521
1.5534752523711128e+06
9.320851514226677e+07
93208515142266763
2012-10-31 15:50:13.793654 +0000 UTC
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时代的相关时间概念。
:::