?
このドキュメントでは、 php中國(guó)語(yǔ)ネットマニュアル リリース
import "time"
概觀
索引
示例
打包時(shí)間提供了測(cè)量和顯示時(shí)間的功能。
日歷計(jì)算總是假定公歷,沒(méi)有閏秒。
操作系統(tǒng)提供了一個(gè)“掛鐘”,它可能會(huì)隨時(shí)鐘同步發(fā)生變化,而“單調(diào)時(shí)鐘”則不會(huì)。一般的規(guī)則是掛鐘是用來(lái)告訴時(shí)間的,而單調(diào)時(shí)鐘是用來(lái)測(cè)量時(shí)間的。Time.Now 包含掛鐘讀數(shù)和單調(diào)時(shí)鐘讀數(shù),而不是拆分 API,在此包裝中, time.Now 返回時(shí)間。后來(lái)的講時(shí)間操作使用掛鐘讀數(shù),但后來(lái)的時(shí)間測(cè)量操作,特別是比較和減法,使用單調(diào)時(shí)鐘讀數(shù)。
例如,即使掛鐘在定時(shí)操作期間發(fā)生變化,該代碼也會(huì)計(jì)算大約20毫秒的積極運(yùn)行時(shí)間:
start := time.Now()... operation that takes 20 milliseconds ...t := time.Now()elapsed := t.Sub(start)
其他成語(yǔ),如 time.Since(開(kāi)始), time.Until(截止日期) 和 time.Now() 。之前(截止日期)對(duì)墻壁時(shí)鐘重置具有類似的魯棒性。
本節(jié)的其余部分給出了操作如何使用單調(diào)時(shí)鐘的精確細(xì)節(jié),但理解這些細(xì)節(jié)并不需要使用該包。
Time.Now 包含單調(diào)時(shí)鐘讀數(shù)。如果時(shí)間 t 具有單調(diào)時(shí)鐘讀數(shù),則 t.Add 將相同的持續(xù)時(shí)間添加到掛鐘和單調(diào)時(shí)鐘讀數(shù)以計(jì)算結(jié)果。因?yàn)?t.AddDate(y, m, d) ,t.Round(d),和t.Truncate(d) 是運(yùn)行時(shí)間計(jì)算,他們總是剝?nèi)ト魏螁握{(diào)時(shí)鐘從它們的結(jié)果讀出。因?yàn)?t.In,t.Local 和 t.UTC 被用于解釋壁掛時(shí)間的效果,所以它們也從其結(jié)果中去除任何單調(diào)的時(shí)鐘讀數(shù)。去除單調(diào)時(shí)鐘讀數(shù)的典型方法是使用 t = t.Round(0)。
如果 Times t 和 u 都包含單調(diào)時(shí)鐘讀數(shù),則單獨(dú)使用單調(diào)時(shí)鐘讀數(shù)來(lái)執(zhí)行操作 t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) ,忽略運(yùn)行時(shí)間讀數(shù)。如果 t 或 u 不包含單調(diào)時(shí)鐘讀數(shù),這些操作將回落到使用掛鐘讀數(shù)。
由于單調(diào)時(shí)鐘讀取在當(dāng)前進(jìn)程之外沒(méi)有任何意義,因此由 t.GobEncode,t.MarshalBinary,t.MarshalJSON和t.MarshalText 生成的序列化表格省略了單調(diào)時(shí)鐘讀取,而 t.Format 不提供任何格式。同樣,構(gòu)造函數(shù) time.Date,time.Parse,time.ParseInLocation 和 time.Unix,以及解組器 t.GobDecode,t.UnmarshalBinary。t.UnmarshalJSON 和 t.UnmarshalText 總是創(chuàng)建沒(méi)有單調(diào)時(shí)鐘讀取的時(shí)間。
請(qǐng)注意,Go == 運(yùn)算符不僅比較時(shí)間,還比較位置和單調(diào)時(shí)鐘讀數(shù)。有關(guān)時(shí)間值相等性測(cè)試的討論,請(qǐng)參閱時(shí)間類型的文檔。
對(duì)于調(diào)試, t.String 的結(jié)果確實(shí)包含單調(diào)時(shí)鐘讀數(shù)(如果存在)。如果由于不同的單調(diào)時(shí)鐘讀數(shù)而導(dǎo)致 t!= u,那么在打印 t.String() 和 u.String() 時(shí)將會(huì)看到這種差異。
常量
func After(d Duration) <-chan Time
func Sleep(d Duration)
func Tick(d Duration) <-chan Time
type Duration
func ParseDuration(s string) (Duration, error)
func Since(t Time) Duration
func Until(t Time) Duration
func (d Duration) Hours() float64
func (d Duration) Minutes() float64
func (d Duration) Nanoseconds() int64
func (d Duration) Round(m Duration) Duration
func (d Duration) Seconds() float64
func (d Duration) String() string
func (d Duration) Truncate(m Duration) Duration
type Location
func FixedZone(name string, offset int) *Location
func LoadLocation(name string) (*Location, error)
func (l *Location) String() string
type Month
func (m Month) String() string
type ParseError
func (e *ParseError) Error() string
type Ticker
func NewTicker(d Duration) *Ticker
func (t *Ticker) Stop()
type Time
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
func Now() Time
func Parse(layout, value string) (Time, error)
func ParseInLocation(layout, value string, loc *Location) (Time, error)
func Unix(sec int64, nsec int64) Time
func (t Time) Add(d Duration) Time
func (t Time) AddDate(years int, months int, days int) Time
func (t Time) After(u Time) bool
func (t Time) AppendFormat(b []byte, layout string) []byte
func (t Time) Before(u Time) bool
func (t Time) Clock() (hour, min, sec int)
func (t Time) Date() (year int, month Month, day int)
func (t Time) Day() int
func (t Time) Equal(u Time) bool
func (t Time) Format(layout string) string
func (t *Time) GobDecode(data []byte) error
func (t Time) GobEncode() ([]byte, error)
func (t Time) Hour() int
func (t Time) ISOWeek() (year, week int)
func (t Time) In(loc *Location) Time
func (t Time) IsZero() bool
func (t Time) Local() Time
func (t Time) Location() *Location
func (t Time) MarshalBinary() ([]byte, error)
func (t Time) MarshalJSON() ([]byte, error)
func (t Time) MarshalText() ([]byte, error)
func (t Time) Minute() int
func (t Time) Month() Month
func (t Time) Nanosecond() int
func (t Time) Round(d Duration) Time
func (t Time) Second() int
func (t Time) String() string
func (t Time) Sub(u Time) Duration
func (t Time) Truncate(d Duration) Time
func (t Time) UTC() Time
func (t Time) Unix() int64
func (t Time) UnixNano() int64
func (t *Time) UnmarshalBinary(data []byte) error
func (t *Time) UnmarshalJSON(data []byte) error
func (t *Time) UnmarshalText(data []byte) error
func (t Time) Weekday() Weekday
func (t Time) Year() int
func (t Time) YearDay() int
func (t Time) Zone() (name string, offset int)
type Timer
func AfterFunc(d Duration, f func()) *Timer
func NewTimer(d Duration) *Timer
func (t *Timer) Reset(d Duration) bool
func (t *Timer) Stop() bool
type Weekday
func (d Weekday) String() string
在日期持續(xù)時(shí)間月份之后 Parse ParseInLocation Sleep Tick Time.Format Time.Round Time.Truncate
format.go sleep.go sys_unix.go tick.go time.go zoneinfo.go zoneinfo_read.go zoneinfo_unix.go
這些是在 Time.Format 和 Time.Parse 中使用的預(yù)定義布局。布局中使用的參考時(shí)間是特定時(shí)間:
Mon Jan 2 15:04:05 MST 2006
這是 Unix 時(shí)間 1136239445 。由于 MST 是 GMT-0700,參考時(shí)間可以被認(rèn)為是
01/02 03:04:05PM '06 -0700
要定義自己的格式,請(qǐng)寫下參考時(shí)間看起來(lái)像格式化的方式; 看例如 ANSIC,StampMicro 或 Kitchen 等常量的值。該模型將演示參考時(shí)間的樣子,以便 Format 和 Parse 方法可以將相同的轉(zhuǎn)換應(yīng)用于一般時(shí)間值。
在格式字符串中,下劃線_表示如果以下數(shù)字(一天)有兩位數(shù)字,則可以用數(shù)字替換空格; 與固定寬度的 Unix 時(shí)間格式兼容。
小數(shù)點(diǎn)后跟一個(gè)或多個(gè)零表示小數(shù)秒,打印到給定的小數(shù)位數(shù)。小數(shù)點(diǎn)后跟一個(gè)或多個(gè)9表示小數(shù)秒,打印到給定的小數(shù)位數(shù),刪除尾隨零。(僅)解析時(shí),即使布局不表示它的存在,輸入可能會(huì)在秒字段之后立即包含小數(shù)第二個(gè)字段。在這種情況下,小數(shù)點(diǎn)后跟最大的一系列數(shù)字將被解析為小數(shù)秒。
數(shù)字時(shí)區(qū)偏移格式如下:
-0700 ±hhmm-07:00 ±hh:mm-07 ±hh
使用 Z 替換格式中的符號(hào)會(huì)觸發(fā)打印 Z 的 ISO 8601行 為,而不是 UTC 區(qū)域的偏移量。從而:
Z0700 Z or ±hhmm Z07:00 Z or ±hh:mm Z07 Z or ±hh
公認(rèn)的星期幾格式是"Mon" 和 "Monday"。公認(rèn)的月份格式是"Jan" 和 "January"。
格式字符串中未被識(shí)別為參考時(shí)間一部分的文本在格式化過(guò)程中逐字回顯,并且預(yù)期在輸入中逐字顯示為解析。
time.Format 的可執(zhí)行示例詳細(xì)說(shuō)明了布局字符串的工作情況,并且是一個(gè)很好的參考。
請(qǐng)注意, RFC822,RFC850 和 RFC1123 格式應(yīng)僅應(yīng)用于當(dāng)?shù)貢r(shí)間。將它們應(yīng)用于 UTC 時(shí)間將使用“UTC”作為時(shí)區(qū)縮寫,而嚴(yán)格來(lái)說(shuō)這些 RFC 在這種情況下需要使用“GMT”。對(duì)于堅(jiān)持這種格式的服務(wù)器,通常應(yīng)該使用 RFC1123Z 而不是 RFC1123Z ,而 RFC3339 應(yīng)該是新協(xié)議的首選。 RFC822,RFC822Z,RFC1123 和 RFC1123Z 對(duì)格式化很有用;當(dāng)與 time.Parse 一起使用時(shí),它們不接受 RFC 允許的所有時(shí)間格式。RFC3339Nano 格式從秒字段中刪除尾隨零,因此格式化后可能無(wú)法正確排序。
const ( ANSIC = "Mon Jan _2 15:04:05 2006" UnixDate = "Mon Jan _2 15:04:05 MST 2006" RubyDate = "Mon Jan 02 15:04:05 -0700 2006" RFC822 = "02 Jan 06 15:04 MST" RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone RFC850 = "Monday, 02-Jan-06 15:04:05 MST" RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST" RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone RFC3339 = "2006-01-02T15:04:05Z07:00" RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00" Kitchen = "3:04PM" // Handy time stamps. Stamp = "Jan _2 15:04:05" StampMilli = "Jan _2 15:04:05.000" StampMicro = "Jan _2 15:04:05.000000" StampNano = "Jan _2 15:04:05.000000000")
func After(d Duration) <-chan Time
在等待持續(xù)時(shí)間后,然后在返回的頻道上發(fā)送當(dāng)前時(shí)間。它相當(dāng)于NewTimer(d).C。在定時(shí)器觸發(fā)之前,底層 Timer 不會(huì)被垃圾收集器恢復(fù)。如果需要提高效率,請(qǐng)改用 NewTimer ,如果不再需要定時(shí)器,則調(diào)用 Timer.Stop。
編碼:
select {case m := <-c: handle(m)case <-time.After(5 * time.Minute): fmt.Println("timed out")}
func Sleep(d Duration)
睡眠暫停當(dāng)前的 goroutine 至少持續(xù)時(shí)間 d 。負(fù)值或零持續(xù)時(shí)間會(huì)導(dǎo)致 Sleep 立即返回。
package mainimport ("time")func main() { time.Sleep(100 * time.Millisecond)}
func Tick(d Duration) <-chan Time
Tick 是 NewTicker 的便捷包裝,僅提供對(duì)滴答聲頻道的訪問(wèn)。雖然 Tick 對(duì)于不需要關(guān)閉 Ticker 的客戶端非常有用,但請(qǐng)注意,如果沒(méi)有辦法關(guān)閉它,底層 Ticker 不能被垃圾收集器恢復(fù); 它“泄漏”。與 NewTicker 不同,如果 d <= 0,Tick 將返回 nil。
編碼:
c := time.Tick(1 * time.Minute)for now := range c { fmt.Printf("%v %s\n", now, statusUpdate())}
持續(xù)時(shí)間表示兩個(gè)瞬間之間的經(jīng)過(guò)時(shí)間,為int64納秒計(jì)數(shù)。該表示將最大的可表示時(shí)間限制在約290年。
type Duration int64
常見(jiàn)的持續(xù)時(shí)間。對(duì)于 Day 或更大單位沒(méi)有定義,以避免在夏令時(shí)時(shí)區(qū)轉(zhuǎn)換時(shí)出現(xiàn)混淆。
要計(jì)算持續(xù)時(shí)間中的單位數(shù)量,請(qǐng)劃分:
second := time.Second fmt.Print(int64(second/time.Millisecond)) // prints 1000
要將整數(shù)個(gè)單位轉(zhuǎn)換為持續(xù)時(shí)間,請(qǐng)乘以:
seconds := 10fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond Minute = 60 * Second Hour = 60 * Minute)
碼:
t0 := time.Now()expensiveCall()t1 := time.Now()fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
func ParseDuration(s string) (Duration, error)
ParseDuration分析持續(xù)時(shí)間字符串。持續(xù)時(shí)間字符串是可能有符號(hào)的十進(jìn)制數(shù)字序列,每個(gè)都有可選的分?jǐn)?shù)和單位后綴,如“300ms”,“-1.5h”或“2h45m”。有效時(shí)間單位為“ns”,“us”(或“μs”),“ms”,“s”,“m”,“h”。
func Since(t Time) Duration
自從返回t以來(lái)的時(shí)間。它是time.Now()。Sub(t)的簡(jiǎn)寫。
func Until(t Time) Duration
直到返回持續(xù)時(shí)間直到t。它是t.Sub(time.Now())的簡(jiǎn)寫。
func (d Duration) Hours() float64
小時(shí)數(shù)將持續(xù)時(shí)間作為浮點(diǎn)小時(shí)數(shù)返回。
func (d Duration) Minutes() float64
分鐘將持續(xù)時(shí)間作為浮點(diǎn)分鐘數(shù)返回。
func (d Duration) Nanoseconds() int64
納秒將持續(xù)時(shí)間作為整數(shù)納秒計(jì)數(shù)返回。
func (d Duration) Round(m Duration) Duration
Round將舍入d的結(jié)果返回到m的最接近的倍數(shù)。中間值的舍入行為是從零開(kāi)始舍入。如果結(jié)果超過(guò)了持續(xù)時(shí)間中可存儲(chǔ)的最大(或最?。┲担瑒t返回最大(或最?。┏掷m(xù)時(shí)間。如果m <= 0,則Round返回d不變。
func (d Duration) Seconds() float64
秒將持續(xù)時(shí)間作為浮點(diǎn)秒數(shù)返回。
func (d Duration) String() string
字符串以“72h3m0.5s”的形式返回一個(gè)表示持續(xù)時(shí)間的字符串。前導(dǎo)零單位被忽略。作為一種特殊情況,小于一秒格式的持續(xù)時(shí)間使用較小的單位(毫秒,微秒或納秒)以確保前導(dǎo)數(shù)字不為零。零持續(xù)時(shí)間格式為0。
func (d Duration) Truncate(m Duration) Duration
截?cái)喾祷厮纳崛雂的結(jié)果為m的倍數(shù)。如果m <= 0,則截?cái)喾祷豥不變。
位置將時(shí)間映射到當(dāng)時(shí)正在使用的區(qū)域。通常情況下,位置表示在某個(gè)地理區(qū)域使用的時(shí)間偏移量集合,例如中歐的CEST和CET。
type Location struct { // contains filtered or unexported fields}
本地代表系統(tǒng)的本地時(shí)區(qū)。
var Local *Location = &localLoc
UTC代表全球協(xié)調(diào)時(shí)間(UTC)。
var UTC *Location = &utcLoc
func FixedZone(name string, offset int) *Location
FixedZone返回一個(gè)始終使用給定區(qū)域名稱和偏移量的位置(UTC以東的秒數(shù))。
func LoadLocation(name string) (*Location, error)
LoadLocation返回具有給定名稱的位置。
如果名稱是“”或“UTC”,則LoadLocation返回UTC。如果名稱是“本地”,則LoadLocation返回本地。
否則,該名稱將被視為與IANA時(shí)區(qū)數(shù)據(jù)庫(kù)中的文件相對(duì)應(yīng)的位置名稱,例如“America / New_York”。
LoadLocation所需的時(shí)區(qū)數(shù)據(jù)庫(kù)可能不存在于所有系統(tǒng)上,尤其是非Unix系統(tǒng)上。LoadLocation查找由ZONEINFO環(huán)境變量命名的目錄或未壓縮的zip文件(如果有),然后查看Unix系統(tǒng)上的已知安裝位置,最后查看$ GOROOT / lib / time / zoneinfo.zip。
func (l *Location) String() string
字符串返回時(shí)區(qū)信息的描述性名稱,對(duì)應(yīng)于LoadLocation或FixedZone的名稱參數(shù)。
一個(gè)月指定一年中的一個(gè)月份(1月= 1,...)。
type Month int
const ( January Month = 1 + iota February March April May June July August September October November December)
package mainimport ("fmt""time")func main() { _, month, day := time.Now().Date()if month == time.November && day == 10 { fmt.Println("Happy Go day!")}}
func (m Month) String() string
字符串返回月份的英文名稱 ("January", "February", ...)。
ParseError 描述解析時(shí)間字符串的問(wèn)題。
type ParseError struct { Layout string Value string LayoutElem string ValueElem string Message string}
func (e *ParseError) Error() string
錯(cuò)誤返回 ParseError 的字符串表示形式。
代碼持有一個(gè)頻道,每隔一段時(shí)間發(fā)送一個(gè)時(shí)鐘的“嘀嗒”。
type Ticker struct { C <-chan Time // The channel on which the ticks are delivered. // contains filtered or unexported fields}
func NewTicker(d Duration) *Ticker
NewTicker 會(huì)返回一個(gè)新的 Ticker ,其中包含一個(gè)頻道,該頻道將使用持續(xù)時(shí)間參數(shù)指定的時(shí)間段發(fā)送時(shí)間。它會(huì)調(diào)整間隔或刪除滴答以彌補(bǔ)慢速接收器。持續(xù)時(shí)間d必須大于零; 如果沒(méi)有, NewTicker 會(huì)驚慌失措。停止代碼以釋放相關(guān)資源。
func (t *Ticker) Stop()
停止關(guān)閉代碼。停止后,不會(huì)再發(fā)送任何蜱蟲(chóng)。停止不關(guān)閉通道,以防止從通道讀取不正確的成功。
時(shí)間以納秒精度表示即時(shí)。
使用時(shí)間的程序通常應(yīng)該存儲(chǔ)并傳遞它們作為值,而不是指針。也就是說(shuō),時(shí)間變量和結(jié)構(gòu)字段的類型應(yīng)該是 time.Time,而不是 * time.Time。
除了方法 GobDecode,UnmarshalBinary,UnmarshalJSON 和 UnmarshalText 不是并發(fā)安全的,一個(gè) Time 值可以被多個(gè) goroutine 同時(shí)使用。
時(shí)間點(diǎn)可以使用 Before,After 和 Equal 方法進(jìn)行比較。Sub 方法減去兩個(gè)瞬間,產(chǎn)生一個(gè)持續(xù)時(shí)間。Add 方法添加一個(gè) Time 和一個(gè) Duration,產(chǎn)生一個(gè) Time。
時(shí)間類型的零值是 UTC 1月1日,1年,00:00:00.000000000。由于這個(gè)時(shí)間不太可能在實(shí)踐中出現(xiàn),IsZero 方法提供了一種簡(jiǎn)單的方法來(lái)檢測(cè)未明確初始化的時(shí)間。
每個(gè)時(shí)間都與它關(guān)聯(lián)一個(gè)位置,在計(jì)算時(shí)間表示形式(例如格式,小時(shí)和年份方法)時(shí)查閱。方法 Local,UTC 和 In 返回具有特定位置的時(shí)間。以這種方式更改位置只會(huì)改變演示文稿; 它不會(huì)改變所指示的時(shí)刻,因此不會(huì)影響前面段落中所述的計(jì)算。
請(qǐng)注意,Go == 運(yùn)算符不僅比較時(shí)間,還比較位置和單調(diào)時(shí)鐘讀數(shù)。因此,如果不首先確保已為所有值設(shè)置了相同的位置(可通過(guò)使用UTC 或 Local 方法實(shí)現(xiàn)),并且單調(diào)時(shí)鐘讀數(shù)已被剝離,則不應(yīng)將時(shí)間值用作地圖或數(shù)據(jù)庫(kù)密鑰設(shè)置 t = t.Round(0) 。一般來(lái)說(shuō),首選 t.Equal(u) 而不是 t == u,因?yàn)?t.Equal 使用可用的最準(zhǔn)確比較,并且只有其中一個(gè)參數(shù)具有單調(diào)時(shí)鐘讀數(shù)時(shí)才能正確處理這種情況。
除了所需的“掛鐘”讀數(shù)外,Time 還可以包含當(dāng)前過(guò)程單調(diào)時(shí)鐘的可選讀數(shù),以提供用于比較或減法的額外精度。有關(guān)詳細(xì)信息,請(qǐng)參閱包裝文檔中的“單調(diào)時(shí)鐘”部分。
type Time struct { // contains filtered or unexported fields}
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
日期返回相應(yīng)的時(shí)間
yyyy-mm-dd hh:mm:ss + nsec nanoseconds
在給定位置的適當(dāng)區(qū)域內(nèi)。
月,日,小時(shí),分鐘,秒和 nsec 值可能超出其通常范圍,并且在轉(zhuǎn)換過(guò)程中將被歸一化。例如,10月32日轉(zhuǎn)換為11月1日。
夏令時(shí)轉(zhuǎn)換跳過(guò)或重復(fù)次數(shù)。例如,在美國(guó),2011年3月13日凌晨2點(diǎn)15分從未發(fā)生過(guò),而2011年11月6日凌晨1點(diǎn)15分發(fā)生了兩次。在這種情況下,時(shí)區(qū)的選擇以及時(shí)間的選擇并不明確。日期返回在轉(zhuǎn)換中涉及的兩個(gè)區(qū)域中的一個(gè)中正確的時(shí)間,但不能保證哪個(gè)時(shí)間。
如果 loc 為 nil ,日期中止。
package mainimport ("fmt""time")func main() { t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) fmt.Printf("Go launched at %s\n", t.Local())}
func Now() Time
現(xiàn)在返回當(dāng)前的本地時(shí)間。
func Parse(layout, value string) (Time, error)
解析解析格式化的字符串并返回它表示的時(shí)間值。布局通過(guò)顯示如何定義參考時(shí)間來(lái)定義格式
Mon Jan 2 15:04:05 -0700 MST 2006
如果它是價(jià)值就會(huì)被解釋;它作為輸入格式的一個(gè)例子。然后對(duì)輸入字符串進(jìn)行相同的解釋。
預(yù)定義的布局 ANSIC,UnixDate,RFC3339 等描述了標(biāo)準(zhǔn)和方便的參考時(shí)間表示。有關(guān)參考時(shí)間的格式和定義的更多信息,請(qǐng)參閱 ANSIC 文檔以及由此包定義的其他常量。此外, time.Format 的可執(zhí)行示例詳細(xì)說(shuō)明了布局字符串的工作情況,并且是一個(gè)很好的參考。
從值中省略的元素被假定為零,或者在0不可能時(shí)為1,因此解析“3:04 pm”將返回與UTC 1月1日,UTC 15:04:00對(duì)應(yīng)的時(shí)間(請(qǐng)注意,由于年份是0,這個(gè)時(shí)間在零時(shí)間之前)。年數(shù)必須在0000到9999的范圍內(nèi)。檢查星期幾的語(yǔ)法,但忽略它。
在沒(méi)有時(shí)區(qū)指示符的情況下,Parse 返回 UTC 時(shí)間。
當(dāng)使用 -0700等區(qū)域偏移量解析時(shí)間時(shí),如果偏移量與當(dāng)前位置(本地)使用的時(shí)區(qū)相對(duì)應(yīng),則 Parse 會(huì)在返回的時(shí)間內(nèi)使用該位置和區(qū)域。否則,它將時(shí)間記錄在固定在給定區(qū)域偏移處的時(shí)間處于制造位置。
在使用區(qū)域縮寫(如MST)解析時(shí)間時(shí),如果區(qū)域縮寫在當(dāng)前位置中具有已定義的偏移量,則會(huì)使用該偏移量。無(wú)論位置如何,區(qū)域縮寫“UTC”都被識(shí)別為 UTC。如果區(qū)域縮寫未知,則 Parse 將時(shí)間記錄為具有給定區(qū)域縮寫和零偏移的制造位置。這種選擇意味著這樣一個(gè)時(shí)間可以無(wú)損地解析和重新格式化為相同的布局,但是在表示中使用的確切時(shí)刻會(huì)因?qū)嶋H的區(qū)域偏移而有所不同。為避免出現(xiàn)此類問(wèn)題,請(qǐng)使用使用數(shù)字區(qū)域偏移量的時(shí)間布局,或使用 ParseInLocation。
編碼:
// See the example for time.Format for a thorough description of how// to define the layout string to parse a time.Time value; Parse and// Format use the same model to describe their input and output.// longForm shows by example how the reference time would be represented in// the desired layout.const longForm = "Jan 2, 2006 at 3:04pm (MST)"t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")fmt.Println(t)// shortForm is another way the reference time would be represented// in the desired layout; it has no time zone present.// Note: without explicit zone, returns time in UTC.const shortForm = "2006-Jan-02"t, _ = time.Parse(shortForm, "2013-Feb-03")fmt.Println(t)
輸出:
2013-02-03 19:54:00 -0800 PST2013-02-03 00:00:00 +0000 UTC
func ParseInLocation(layout, value string, loc *Location) (Time, error)
ParseInLocation 類似于 Parse,但在兩個(gè)重要方面有所不同。首先,在沒(méi)有時(shí)區(qū)信息的情況下,Parse 將時(shí)間解釋為 UTC;ParseInLocation 按照給定位置解釋時(shí)間。其次,當(dāng)給定區(qū)域偏移或縮寫時(shí),Parse 會(huì)嘗試將其與本地位置進(jìn)行匹配; ParseInLocation 使用給定的位置。
編碼:
loc, _ := time.LoadLocation("Europe/Berlin")const longForm = "Jan 2, 2006 at 3:04pm (MST)"t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)fmt.Println(t)// Note: without explicit zone, returns time in given location.const shortForm = "2006-Jan-02"t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)fmt.Println(t)
輸出:
2012-07-09 05:02:00 +0200 CEST2012-07-09 00:00:00 +0200 CEST
func Unix(sec int64, nsec int64) Time
Unix 返回與給定的 Unix 時(shí)間相對(duì)應(yīng)的本地時(shí)間,自1970年1月1日 UTC 以來(lái)秒數(shù)和納秒。在范圍0,999999999之外傳遞nsec是有效的。并非所有 sec 值都具有相應(yīng)的時(shí)間值。一個(gè)這樣的值是1 << 63-1(最大的int64值)。
func (t Time) Add(d Duration) Time
添加返回時(shí)間 t + d。
func (t Time) AddDate(years int, months int, days int) Time
AddDate 返回相應(yīng)于將給定年數(shù),月份和天數(shù)添加到t的時(shí)間。例如,2011年1月1日應(yīng)用的 AddDate(-1,2,3) 將返回2010年3月4日。
AddDate 使用與 Date 相同的方式對(duì)其結(jié)果進(jìn)行規(guī)范化,因此,例如,在10月31日之前增加一個(gè)月會(huì)產(chǎn)生12月1日,即11月31日的規(guī)范化表單。
func (t Time) After(u Time) bool
在報(bào)告時(shí)刻 t 是否在 u 之后。
func (t Time) AppendFormat(b []byte, layout string) []byte
AppendFormat 與 Format 相似,但將文本表示附加到 b 并返回?cái)U(kuò)展緩沖區(qū)。
func (t Time) Before(u Time) bool
在報(bào)告時(shí)刻 t 是否在你之前。
func (t Time) Clock() (hour, min, sec int)
時(shí)鐘在 t 指定的日期內(nèi)返回小時(shí),分鐘和秒。
func (t Time) Date() (year int, month Month, day int)
日期返回出現(xiàn) t 的年份,月份和日期。
func (t Time) Day() int
Day 返回由 t 指定的月份的一天。
func (t Time) Equal(u Time) bool
Equal 報(bào)告 t 和 u 是否表示同一時(shí)刻。即使他們?cè)诓煌牡攸c(diǎn),兩次也是平等的。例如,6:00 +0200 CEST和4:00 UTC 是 Equal。有關(guān)使用時(shí)間值 == 的缺陷,請(qǐng)參閱時(shí)間類型的文檔; 大多數(shù)代碼應(yīng)該使用 Equal。
func (t Time) Format(layout string) string
格式返回按照布局格式化的時(shí)間值的文本表示,該格式通過(guò)顯示如何定義參考時(shí)間來(lái)定義格式
Mon Jan 2 15:04:05 -0700 MST 2006
如果它是值,則會(huì)顯示;它充當(dāng)期望輸出的一個(gè)例子。然后將相同的顯示規(guī)則應(yīng)用于時(shí)間值。
通過(guò)在布局字符串的秒部分的末尾添加句點(diǎn)和零來(lái)表示分?jǐn)?shù)秒,如“15:04:05.000”中所示,以毫秒精度格式化時(shí)間戳。
預(yù)定義的布局ANSIC,UnixDate,RFC3339等描述了標(biāo)準(zhǔn)和方便的參考時(shí)間表示。有關(guān)參考時(shí)間的格式和定義的更多信息,請(qǐng)參閱 ANSIC 文檔以及由此包定義的其他常量。
package mainimport ("fmt""time")func main() {// Parse a time value from a string in the standard Unix format. t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")if err != nil { // Always check errors even if they should not happen.panic(err)}// time.Time's Stringer method is useful without any format. fmt.Println("default format:", t)// Predefined constants in the package implement common layouts. fmt.Println("Unix format:", t.Format(time.UnixDate))// The time zone attached to the time value affects its output. fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))// The rest of this function demonstrates the properties of the// layout string used in the format.// The layout string used by the Parse function and Format method// shows by example how the reference time should be represented.// We stress that one must show how the reference time is formatted,// not a time of the user's choosing. Thus each layout string is a// representation of the time stamp,// Jan 2 15:04:05 2006 MST// An easy way to remember this value is that it holds, when presented// in this order, the values (lined up with the elements above):// 1 2 3 4 5 6 -7// There are some wrinkles illustrated below.// Most uses of Format and Parse use constant layout strings such as// the ones defined in this package, but the interface is flexible,// as these examples show.// Define a helper function to make the examples' output look nice.do := func(name, layout, want string) { got := t.Format(layout)if want != got { fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)return} fmt.Printf("%-15s %q gives %q\n", name, layout, got)}// Print a header in our output. fmt.Printf("\nFormats:\n\n")// A simple starter example.do("Basic", "Mon Jan 2 15:04:05 MST 2006", "Sat Mar 7 11:06:39 PST 2015")// For fixed-width printing of values, such as the date, that may be one or// two characters (7 vs. 07), use an _ instead of a space in the layout string.// Here we print just the day, which is 2 in our layout string and 7 in our// value.do("No pad", "<2>", "<7>")// An underscore represents a zero pad, if required.do("Spaces", "<_2>", "< 7>")// Similarly, a 0 indicates zero padding.do("Zeros", "<02>", "<07>")// If the value is already the right width, padding is not used.// For instance, the second (05 in the reference time) in our value is 39,// so it doesn't need padding, but the minutes (04, 06) does.do("Suppressed pad", "04:05", "06:39")// The predefined constant Unix uses an underscore to pad the day.// Compare with our simple starter example.do("Unix", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")// The hour of the reference time is 15, or 3PM. The layout can express// it either way, and since our value is the morning we should see it as// an AM time. We show both in one format string. Lower case too.do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")// When parsing, if the seconds value is followed by a decimal point// and some digits, that is taken as a fraction of a second even if// the layout string does not represent the fractional second.// Here we add a fractional second to our time value used above. t, err = time.Parse(time.UnixDate, "Sat Mar 7 11:06:39.1234 PST 2015")if err != nil {panic(err)}// It does not appear in the output if the layout string does not contain// a representation of the fractional second.do("No fraction", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")// Fractional seconds can be printed by adding a run of 0s or 9s after// a decimal point in the seconds value in the layout string.// If the layout digits are 0s, the fractional second is of the specified// width. Note that the output has a trailing zero.do("0s for fraction", "15:04:05.00000", "11:06:39.12340")// If the fraction in the layout is 9s, trailing zeros are dropped.do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")}
func (t *Time) GobDecode(data []byte) error
GobDecode 實(shí)現(xiàn)了 gob.GobDecoder 接口。
func (t Time) GobEncode() ([]byte, error)
GobEncode 實(shí)現(xiàn) gob.GobEncoder 接口。
func (t Time) Hour() int
小時(shí)返回 t 指定的一天內(nèi)的小時(shí)數(shù),范圍為0,23(0到23)。
func (t Time) ISOWeek() (year, week int)
ISOWeek 返回 t 發(fā)生的 ISO 8601 年和周數(shù)。周的范圍為 1至53.n年的01月01日至03年1月03日可能屬于n-1年的第52或53周,而12月29日至12月31日可能屬于第 n + 1 年的第1周。
func (t Time) In(loc *Location) Time
在返回 t 時(shí),位置信息設(shè)置為 loc。
在中止情況下,如果 loc 為 nil 。
func (t Time) IsZero() bool
IsZero 報(bào)告 t 是否表示 UTC 時(shí)間1月1日,1日00:00:00的零時(shí)刻。
func (t Time) Local() Time
本地返回 t ,其位置設(shè)置為當(dāng)?shù)貢r(shí)間。
func (t Time) Location() *Location
位置返回與 t 關(guān)聯(lián)的時(shí)區(qū)信息。
func (t Time) MarshalBinary() ([]byte, error)
MarshalBinary 實(shí)現(xiàn)了 encoding.BinaryMarshaler 接口。
func (t Time) MarshalJSON() ([]byte, error)
MarshalJSON 實(shí)現(xiàn)了 json.Marshaler 接口。時(shí)間是以 RFC 3339 格式引用的字符串,如果存在,則添加亞秒精度。
func (t Time) MarshalText() ([]byte, error)
MarshalText 實(shí)現(xiàn)了 encoding.TextMarshaler 接口。時(shí)間格式為 RFC 3339 格式,如果存在,則會(huì)添加亞秒精度。
func (t Time) Minute() int
分鐘返回由 t 指定的小時(shí)內(nèi)的分鐘偏移量,范圍為0,59(0到59)。
func (t Time) Month() Month
月返回由 t 指定的年份的月份。
func (t Time) Nanosecond() int
毫微秒返回由秒指定的秒內(nèi)的納秒偏移量,范圍為0,999999999(0到999999999)。
func (t Time) Round(d Duration) Time
Round 將舍入 t 的結(jié)果返回到 d 的最近倍數(shù)(自零時(shí)間起)。中途值的舍入行為是四舍五入的。如果 d <= 0,Round 將返回t中的任何單調(diào)時(shí)鐘讀數(shù),但不改變。
Round 在零時(shí)間之后作為絕對(duì)持續(xù)時(shí)間運(yùn)行; 它不適用于當(dāng)時(shí)的演示文稿格式。因此, Round(Hour) 可能會(huì)返回非零分鐘的時(shí)間,具體取決于時(shí)間的位置。
package mainimport ("fmt""time")func main() { t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC) round := []time.Duration{ time.Nanosecond, time.Microsecond, time.Millisecond, time.Second,2 * time.Second, time.Minute,10 * time.Minute, time.Hour,}for _, d := range round { fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))}}
func (t Time) Second() int
第二個(gè)返回由 t 指定的分鐘內(nèi)的第二個(gè)偏移量,范圍為0,59(0到59)。
func (t Time) String() string
字符串返回使用格式字符串格式化的時(shí)間
"2006-01-02 15:04:05.999999999 -0700 MST"
如果時(shí)間具有單調(diào)時(shí)鐘讀數(shù),則返回的字符串包含最終字段“m =±<value>”,其中 value 是單調(diào)時(shí)鐘讀數(shù),格式為十進(jìn)制秒數(shù)。
返回的字符串用于調(diào)試;對(duì)于穩(wěn)定的序列化表示,請(qǐng)使用帶明確格式字符串的 t.MarshalText,t.MarshalBinary 或 t.Format 。
func (t Time) Sub(u Time) Duration
Sub 返回持續(xù)時(shí)間 t-u 。如果結(jié)果超過(guò)持續(xù)時(shí)間中可存儲(chǔ)的最大(或最小)值,則會(huì)返回最大(或最小)持續(xù)時(shí)間。要計(jì)算持續(xù)時(shí)間 d 的 t-d,請(qǐng)使用 t.Add(-d)。
func (t Time) Truncate(d Duration) Time
截?cái)鄬⑸崛?t 的結(jié)果返回到 d 的倍數(shù)(自零時(shí)間起)。如果 d <= 0,則截?cái)喾祷爻ト魏螁握{(diào)時(shí)鐘讀數(shù)的 t ,否則不變。
截?cái)嗖僮鲿r(shí)間為自零時(shí)間以來(lái)的絕對(duì)持續(xù)時(shí)間; 它不適用于當(dāng)時(shí)的演示文稿格式。因此,根據(jù)時(shí)間的位置,截?cái)啵ㄐr(shí))可能會(huì)返回一個(gè)非零分鐘的時(shí)間。
編碼:
t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")trunc := []time.Duration{ time.Nanosecond, time.Microsecond, time.Millisecond, time.Second, 2 * time.Second, time.Minute, 10 * time.Minute,}for _, d := range trunc { fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))}// To round to the last midnight in the local timezone, create a new Date.midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)_ = midnight
輸出:
t.Truncate( 1ns) = 12:15:30.918273645t.Truncate( 1μs) = 12:15:30.918273t.Truncate( 1ms) = 12:15:30.918t.Truncate( 1s) = 12:15:30t.Truncate( 2s) = 12:15:30t.Truncate( 1m0s) = 12:15:00t.Truncate(10m0s) = 12:10:00
func (t Time) UTC() Time
UTC 將位置設(shè)置為 UTC 時(shí)返回 t 。
func (t Time) Unix() int64
Unix 將 t 作為 Unix 時(shí)間返回,即 UTC 自1970年1月1日以來(lái)經(jīng)過(guò)的秒數(shù)。
func (t Time) UnixNano() int64
UnixNano 返回 t 作為 Unix 時(shí)間,自 UTC 1970年1月1日起經(jīng)過(guò)的納秒數(shù)。如果 Unix 時(shí)間(納秒)不能用 int64(1678年之前或2262之后的日期)表示,結(jié)果是不確定的。請(qǐng)注意,這意味著在零時(shí)間調(diào)用 UnixNano 的結(jié)果是未定義的。
func (t *Time) UnmarshalBinary(data []byte) error
UnmarshalBinary 實(shí)現(xiàn)了 encoding.BinaryUnmarshaler 接口。
func (t *Time) UnmarshalJSON(data []byte) error
UnmarshalJSON 實(shí)現(xiàn)了 json.Unmarshaler 接口。預(yù)計(jì)該時(shí)間是 RFC 3339 格式中的帶引號(hào)的字符串。
func (t *Time) UnmarshalText(data []byte) error
UnmarshalText 實(shí)現(xiàn)了 encoding.TextUnmarshaler 接口。預(yù)計(jì)時(shí)間將采用 RFC 3339 格式。
func (t Time) Weekday() Weekday
平日返回由 t 指定的星期幾。
func (t Time) Year() int
年份返回 t 發(fā)生的年份。
func (t Time) YearDay() int
YearDay 返回 t 指定的年份中的某一天,非閏年為 1,365,閏年為 1,366。
func (t Time) Zone() (name string, offset int)
Zone 計(jì)算在時(shí)間 t 有效的時(shí)區(qū),并返回該區(qū)域的縮寫名稱(如“CET”)及其在 UTC 以東秒的偏移量。
Timer 類型表示一個(gè)事件。當(dāng)定時(shí)器到期時(shí),當(dāng)前時(shí)間將在 C 上發(fā)送,除非定時(shí)器是由 AfterFunc 創(chuàng)建的。定時(shí)器必須使用 NewTimer 或 AfterFunc 創(chuàng)建。
type Timer struct { C <-chan Time // contains filtered or unexported fields}
func AfterFunc(d Duration, f func()) *Timer
AfterFunc 等待持續(xù)時(shí)間,然后在自己的 goroutine 中調(diào)用 f 。它返回一個(gè) Timer ,它可以用來(lái)使用 Stop 方法取消調(diào)用。
func NewTimer(d Duration) *Timer
NewTimer 創(chuàng)建一個(gè)新的定時(shí)器,在至少持續(xù)時(shí)間 d 后,它將在其通道上發(fā)送當(dāng)前時(shí)間。
func (t *Timer) Reset(d Duration) bool
重置更改定時(shí)器在持續(xù)時(shí)間 d 后過(guò)期。如果定時(shí)器處于活動(dòng)狀態(tài),則返回 true ;如果定時(shí)器已到期或已停止,則返回 false 。
復(fù)位定時(shí)器必須注意不要與當(dāng)前定時(shí)器到期時(shí)發(fā)送的 t.C 競(jìng)爭(zhēng)。如果一個(gè)程序已經(jīng)從 t.C 接收到一個(gè)值,定時(shí)器已知已經(jīng)過(guò)期,并且 t.Reset 可以直接使用。但是,如果程序尚未從 t.C 接收到值,則必須停止定時(shí)器,并且——如果 Stop 在停止之前報(bào)告定時(shí)器已過(guò)期 ——?jiǎng)t明確排空通道:
if !t.Stop() {<-t.C}t.Reset(d)
這不應(yīng)該與來(lái)自定時(shí)器通道的其他接收同時(shí)完成。
請(qǐng)注意,無(wú)法正確使用重置的返回值,因?yàn)榕懦鐾ǖ篮托露〞r(shí)器到期之間存在爭(zhēng)用情況。如上所述,應(yīng)始終在已停止或已到期的渠道上調(diào)用重置。返回值的存在是為了保持與現(xiàn)有程序的兼容性。
func (t *Timer) Stop() bool
停止防止定時(shí)器發(fā)射。如果調(diào)用停止定時(shí)器,則返回 true ;如果定時(shí)器已經(jīng)過(guò)期或停止,則返回 false 。停止不關(guān)閉通道,以防止從通道讀取不正確的成功。
為了防止在調(diào)用 Stop 之后使用 NewTimer 創(chuàng)建的定時(shí)器觸發(fā),請(qǐng)檢查返回值并排空通道。例如,假設(shè)程序尚未從 t.C 收到:
if !t.Stop() {<-t.C}
這不能與來(lái)自定時(shí)器通道的其他接收同時(shí)完成。
對(duì)于使用 AfterFunc(d,f) 創(chuàng)建的定時(shí)器,如果 t.Stop 返回 false ,則定時(shí)器已經(jīng)過(guò)期并且函數(shù)f已經(jīng)在其自己的 goroutine 中啟動(dòng);在返回之前停止不等待 f 完成。如果調(diào)用者需要知道f是否完成,則必須明確地與f協(xié)調(diào)。
星期幾指定星期幾(星期日= 0,...)。
type Weekday int
const ( Sunday Weekday = iota Monday Tuesday Wednesday Thursday Friday Saturday)
func (d Weekday) String() string
字符串返回當(dāng)天的英文名稱 ("Sunday", "Monday", ...) 。