Files
the-way-to-go_ZH_CN/eBook/04.8.md
2013-06-18 10:05:21 +08:00

54 lines
2.5 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.Now()**,想得到时间的一部分,可以使用 t.Day()t.Minute()等等;你也可以使用自己的时间格式化如: **fmt.Printf("%02d.%02d.%4d\n”, t.Day(), t.Month(), t.Year())** // 例如21.07.2011
Duration类型表示连续时间的两个时刻的纳秒数。Location类型映射了那个时区的时间UTC表示通用协调世界时。
有一个预定义的函数`func (t Time) Format(layout string) string` 可以根据一个格式字符串,将一个时间 t 格式化为一个字符串,格式使用预定义的格式如 `time.ANSIC``time.RFC822`
一般的格式化,定义了标准的时间格式,它将被用于描述被格式化的时间格式;这看来很奇怪,但是例子可以使他更清晰:
fmt.Println(t.Format(“02 Jan 2006 15:04”)) // outputs now: 21 Jul 2011 10:31
(参见程序 time.go更多信息在 http://golang.org/pkg/time/
Listing 4.20—time.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中参见§14.1)一个持续时间 d。
##链接
- [目录](directory.md)
- 上一节:[strings 和 strconv 包](04.7.md)
- 下一节:[指针](04.9.md)