在线文档  >   Golang练习   >   时间

Go语言提供了丰富的时间和持续时间(duration)支持;以下是一些示例。

package main

import (
    "fmt"
    "time"
)

func main() {
    p := fmt.Println

    // 首先,我们获取当前时间。
    now := time.Now()
    p(now)

    // 你可以通过提供年、月、日等参数来构建一个`tme`结构。
    // 时间总是与`Location`,也就是时区相关联。
    then := time.Date(
        2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
    p(then)

    // 你可以像预期的那样提取时间值的各个组件。
    p(then.Year())
    p(then.Month())
    p(then.Day())
    p(then.Hour())
    p(then.Minute())
    p(then.Second())
    p(then.Nanosecond())
    p(then.Location())

    // 还可以获得星期几(Monday-Sunday)。
    p(then.Weekday())

    // 这些方法比较两个时间,分别测试第一个是否发生在第二个之前、之后或同时。
    p(then.Before(now))
    p(then.After(now))
    p(then.Equal(now))

    // `Sub`方法返回代表两个时间间隔的`Duration`。
    diff := now.Sub(then)
    p(diff)

    // 我们可以用不同单位计算持续时间的长度。
    p(diff.Hours())
    p(diff.Minutes())
    p(diff.Seconds())
    p(diff.Nanoseconds())

    // 你可以使用`Add`来扩展一个给定的时间以及一段持续时间,或者使用`-`来向后移动一段持续时间。
    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

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