Go 支援透過基於樣式的配置進行時間格式化和剖析。
|
|
|

package main
|
|
import (
"fmt"
"time"
)
|
|
func main() {
p := fmt.Println
|
以下是使用對應配置常數,根據 RFC3339 格式化時間的基本範例。
|
t := time.Now()
p(t.Format(time.RFC3339))
|
時間剖析使用與 Format 相同的配置值。
|
t1, e := time.Parse(
time.RFC3339,
"2012-11-01T22:08:41+00:00")
p(t1)
|
Format 和 Parse 使用基於範例的配置。通常你會為這些配置使用 time 中的常數,但你也可以提供自訂配置。配置必須使用參考時間 Mon Jan 2 15:04:05 MST 2006 來顯示要格式化/剖析特定時間/字串的樣式。範例時間必須完全如顯示所示:年份為 2006、小時為 15、星期為星期一等。
|
p(t.Format("3:04PM"))
p(t.Format("Mon Jan _2 15:04:05 2006"))
p(t.Format("2006-01-02T15:04:05.999999-07:00"))
form := "3 04 PM"
t2, e := time.Parse(form, "8 41 PM")
p(t2)
|
對於純數值表示方式,你也可以搭配時間值中萃取的元件使用標準字串格式化。
|
fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
|
Parse 會對格式錯誤的輸入傳回錯誤,說明剖析問題。
|
ansic := "Mon Jan _2 15:04:05 2006"
_, e = time.Parse(ansic, "8:41PM")
p(e)
}
|