Files
the-way-to-go_ZH_CN/eBook/04.8.md
2015-07-14 16:36:08 +08:00

64 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 4.8 时间和日期
`time` 包为我们提供了一个数据类型 `time.Time`(作为值使用)以及显示和测量时间和日期的功能函数。
当前时间可以使用 `time.Now()` 获取,或者使用 `t.Day()``t.Minute()` 等等来获取时间的一部分;你甚至可以自定义时间格式化字符串,例如: `fmt.Printf("%02d.%02d.%4d\n", t.Day(), t.Month(), t.Year())` 将会输出 `21.07.2011`
Duration 类型表示两个连续时刻所相差的纳秒数,类型为 int64。Location 类型映射某个时区的时间UTC 表示通用协调世界时间。
包中的一个预定义函数 `func (t Time) Format(layout string) string` 可以根据一个格式化字符串来将一个时间 t 转换为相应格式的字符串,你可以使用一些预定义的格式,如:`time.ANSIC``time.RFC822`
一般的格式化设计是通过对于一个标准时间的格式化描述来展现的,这听起来很奇怪,但看下面这个例子你就会一目了然:
```go
fmt.Println(t.Format("02 Jan 2006 15:04"))
```
输出:
21 Jul 2011 10:31
其它有关时间操作的文档请参阅 [官方文档](http://golang.org/pkg/time/) **译者注:国内用户可访问 [该页面](http://docs.studygolang.com/pkg/time/)** )。
示例 4.20 [time.go](examples/chapter_4/time.go)
```go
package main
import (
"fmt"
"time"
)
var week time.Duration
func main() {
t := time.Now()
fmt.Println(t) // e.g. Wed Dec 21 09:52:14 +0100 RST 2011
fmt.Printf("%02d.%02d.%4d\n", t.Day(), t.Month(), t.Year())
// 21.12.2011
t = time.Now().UTC()
fmt.Println(t) // Wed Dec 21 08:52:14 +0000 UTC 2011
fmt.Println(time.Now()) // Wed Dec 21 09:52:14 +0100 RST 2011
// calculating times:
week = 60 * 60 * 24 * 7 * 1e9 // must be in nanosec
week_from_now := t.Add(week)
fmt.Println(week_from_now) // Wed Dec 28 08:52:14 +0000 UTC 2011
// formatting times:
fmt.Println(t.Format(time.RFC822)) // 21 Dec 11 0852 UTC
fmt.Println(t.Format(time.ANSIC)) // Wed Dec 21 08:56:34 2011
fmt.Println(t.Format("02 Jan 2006 15:04")) // 21 Dec 2011 08:52
s := t.Format("20060102")
fmt.Println(t, "=>", s)
// Wed Dec 21 08:52:14 +0000 UTC 2011 => 20111221
}
```
输出的结果已经写在每行 `//` 的后面。
如果你需要在应用程序在经过一定时间或周期执行某项任务(事件处理的特例),则可以使用 `time.After` 或者 `time.Ticker`:我们将会在第 14.5 节讨论这些有趣的事情。 另外,`time.SleepDuration d` 可以实现对某个进程(实质上是 goroutine时长为 d 的暂停。
## 链接
- [目录](directory.md)
- 上一节:[strings 和 strconv 包](04.7.md)
- 下一节:[指针](04.9.md)