主要是 time
包(2021/05/21,Golang time
包)。
time.Time
时间,精确到纳秒time.Location
时区-
time.Duration
时间间隔,精确到纳秒,[-292.47 years, 292.47 years](1 << 63) / 1_000_000_000 / 3600 / 24 / 365 292.471208677536
src/time/time.go:type Time struct {
src/time/time.go- wall uint64 // 秒 wall time seconds
src/time/time.go- ext int64 // 毫秒 wall time nanoseconds
src/time/time.go- loc *Location // 时区
src/time/time.go-}
src/time/zoneinfo.go:type Location struct {
src/time/zoneinfo.go- name string
src/time/zoneinfo.go- zone []zone
src/time/zoneinfo.go- tx []zoneTrans
src/time/zoneinfo.go- extend string
src/time/zoneinfo.go- cacheStart int64
src/time/zoneinfo.go- cacheEnd int64
src/time/zoneinfo.go- cacheZone *zone
src/time/zoneinfo.go-}
src/time/zoneinfo.go:type zone struct {
src/time/zoneinfo.go- name string // abbreviated name, "CET"
src/time/zoneinfo.go- offset int // seconds east of UTC
src/time/zoneinfo.go- isDST bool // is this zone Daylight Savings Time?
src/time/zoneinfo.go-}
src/time/zoneinfo.go-type zoneTrans struct {
src/time/zoneinfo.go- when int64 // transition time, in seconds since 1970 GMT
src/time/zoneinfo.go- index uint8 // the index of the zone that goes into effect at that time
src/time/zoneinfo.go- isstd, isutc bool // ignored - no idea what these mean
src/time/zoneinfo.go-}
var UTC *Location = &utcLoc
var utcLoc = Location{name: "UTC"}
var Local *Location = &localLoc
var localLoc Location
src/time/time.go:type Duration int64
基本用法
time.Now() // time.Time
// type Month int
// const (
// January Month = 1 + iota
// February
// March
// April
// May
// June
// July
// August
// September
// October
// November
// December
// )
// var Local *Location = &localLoc
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time // 组装 Time
// Time -> 时间戳
time.Now().Unix() // int64
time.Now().UnixMilli() // int64 毫秒
time.Now().UnixMicro() // int64 微秒
time.Now().UnixNano() // int64 纳秒
func Unix(sec int64, nsec int64) Time // 时间戳 -> Time
time.Now().Format("2006-01-02 15:04:05") // Time -> timestr
timeObj, erro := time.Parse("2006-01-02 15:04:05", timestr) // timestr -> Time
// 特别注意:time.Parse 是按照 UTC 时区解析
timeObj, erro := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
间隔计算
func (t Time) Truncate(d Duration) Time
func (t Time) Round(d Duration) Time
func (d Duration) Truncate(m Duration) Duration
func (d Duration) Round(m Duration) Duration
func (t Time) Add(d Duration) Time // Time 相加
func (t Time) Sub(u Time) Duration // Time 相减
func Since(t Time) Duration // Now - t
func Until(t Time) Duration // t - Now
time.Now().Truncate(时间)
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Hello, 世界")
now := time.Date(2021, 5, 21, 15, 46, 47, 0, time.Local)
fmt.Println(now)
// d := time.Hour
d := time.Duration(3000_000_000_000)
fmt.Println(now.Truncate(d))
fmt.Println(now.Round(d))
}
// 2021-05-21 15:46:47 +0000 UTC
// 2021-05-21 15:00:00 +0000 UTC
// 2021-05-21 15:50:00 +0000 UTC