golang 时间格式化

630 阅读3分钟

基本时间格式示例

Go不使用yyyy-mm-dd布局来格式化或解析时间。而是格式化一个特殊的布局参数
Mon Jan 2 15:04:05 MST 2006

与格式化时间或日期的方式相同。(这个日期在写成时更容易记住01/02 03:04:05PM ‘06 -0700。)

const (
    layoutISO = "2006-01-02"
    layoutUS  = "January 2, 2006"
)
date := "1999-12-31"
t, _ := time.Parse(layoutISO, date)
fmt.Println(t)                  // 1999-12-31 00:00:00 +0000 UTC
fmt.Println(t.Format(layoutUS)) // December 31, 1999

12345678

函数

  • time.Parse 解析日期字符串
  • Format格式化 time.Time。

他们有以下用法:

func Parse(layout, value string) (Time, error)
func (t Time) Format(layout string) string

12

常见的时间和日期布局

LayoutNote
January 2, 2006 01/02/06 Jan-02-06Date
15:04:05 3:04:05 PMTime
Jan _2 15:04:05 Jan _2 15:04:05.000000Timestamp with microseconds
2006-01-02T15:04:05-0700 2006-01-02 15:04:05ISO 8601 (RFC 3339)
02 Jan 06 15:04 MST 02 Jan 06 15:04 -0700RFC 822 with numeric zone

预定义的日期和时间戳布局

还可以使用以下预定义格式常量。

ANSIC =“Mon Jan _2 15:04:05 2006UnixDate =“Mon Jan _2 15:04:05 MST 2006RubyDate =“Mon Jan 02 15:04:05 -0700 2006RFC822 =“02 Jan 06 15:04 MST”
RFC822Z =“02 Jan 06 15:04 -0700RFC850 =“星期一,02-Jan-06 15:04:05 MST”
RFC1123 =“星期一,20061215:04:05 MST”
RFC1123Z =“星期一,20061215:04:05 -0700RFC3339 =“2006-01-02T15:0405Z07:00RFC3339Nano =“2006-01-02T15:0405.999999999Z07:00”
厨房=“下午3:04”
//便利的时间戳。
邮票=“Jan _2 15:04:05”
StampMilli =“Jan _2 150405.000StampMicro =“Jan _2 150405.000000StampNano =“Jan _2 150405.000000000”

12345678910111213141516

所有layout选项

TypeOptions
Year Month Day Weekday06 2006 01 1 Jan January 02 2 _2 (width two, right justified) Mon Monday
Hours Minutes Seconds ms μs ns ms μs ns03 3 15 04 4 05 5 .000 .000000 .000000000 .999 .999999 .999999999 (trailing zeros removed)
am/pmPM pm
Timezone OffsetMST -0700 -07 -07:00 Z0700 Z07:00

小案例

在24小时时间格式中,不可能指定在没有前缀零的情况下渲染一个小时。

不可能指定午夜为24:00,得用00:00。一个典型的用法是使用开区间时间在午夜结束,例如07:00-24:00。(译者注:使用24:00会报错hour out of range)

无法指定包含闰秒(leap second)的时间:23:59:60。实际上,时间包假设没有闰秒的公历。