Go編程為時(shí)間和持續(xù)時(shí)間提供廣泛的支持; 這里有些例子。我們將從獲取當(dāng)前時(shí)間開(kāi)始。也可以通過(guò)提供年,月,日等來(lái)構(gòu)建時(shí)間結(jié)構(gòu)。時(shí)間總是與位置(即時(shí)區(qū))相關(guān)聯(lián)。
具體的每個(gè)函數(shù),可參考示例中的代碼 -
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.com/go/go_environment.html
json.go的完整代碼如下所示 -
package main
import "fmt"
import "time"
func main() {
p := fmt.Println
// We'll start by getting the current time.
now := time.Now()
p(now)
// You can build a `time` struct by providing the
// year, month, day, etc. Times are always associated
// with a `Location`, i.e. time zone.
then := time.Date(
2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
p(then)
// You can extract the various components of the time
// value as expected.
p(then.Year())
p(then.Month())
p(then.Day())
p(then.Hour())
p(then.Minute())
p(then.Second())
p(then.Nanosecond())
p(then.Location())
// The Monday-Sunday `Weekday` is also available.
p(then.Weekday())
// These methods compare two times, testing if the
// first occurs before, after, or at the same time
// as the second, respectively.
p(then.Before(now))
p(then.After(now))
p(then.Equal(now))
// The `Sub` methods returns a `Duration` representing
// the interval between two times.
diff := now.Sub(then)
p(diff)
// We can compute the length of the duration in
// various units.
p(diff.Hours())
p(diff.Minutes())
p(diff.Seconds())
p(diff.Nanoseconds())
// You can use `Add` to advance a time by a given
// duration, or with a `-` to move backwards by a
// duration.
p(then.Add(diff))
p(then.Add(-diff))
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run time.go
2017-01-21 16:59:10.8307711 +0800 CST
2009-11-17 20:34:58.651387237 +0000 UTC
2009
November
17
20
34
58
651387237
UTC
Tuesday
true
false
false
62916h24m12.179383863s
62916.403383162185
3.774984202989731e+06
2.2649905217938387e+08
226499052179383863
2017-01-21 08:59:10.8307711 +0000 UTC
2002-09-14 08:10:46.472003374 +0000 UTC