golang 的時間格式化操作

2022-05-22 09:30:14 字數 2263 閱讀 2654

time.now().format("2006-01-02 15:04:05")
你將會獲得如同yyyy-mm-dd hh-mm-ss這樣的輸出。

在 format.go 的原始碼中我們可以找到一些預定的格式,原始碼摘抄如下:

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"

)

我們可以直接使用time.time物件的format函式,將以上預定的格式當作引數,來得到格式化後的時間字串。

除了預定義的格式,我們也可以按照上述格式的規則自定義格式化字串,就如同上一節 「簡而言之」 中描述的那樣。

golang的時間格式化並不像c#那樣使用yyyy表示年份、mm表示月份等等。

而是使用2006-01-02 15:04:05這樣具有固定數字的格式化字串。

你要問我為什麼使用這樣看起來奇怪的格式化字串?抱歉,我真的猜不透。

下面的**摘自golang源** 關於時間格式化的部分

// string returns the time formatted using the format string

// "2006-01-02 15:04:05.999999999 -0700 mst"

func (t time) string() string

可以看到,golang中並沒有使用英文單詞首字母表示的格式化字串,而是使用了一組固定的資料。

在 format.go 中第140行左右的地方,可以找到下面這個函式。

此函式用來判斷格式化字串中的格式化內容。在其源**中,我們可以清晰地看到, golang 使用了硬編碼來對格式化字串進行判斷。

// nextstdchunk finds the first occurrence of a std string in

// layout and returns the text before, the std string, and the text after.

func nextstdchunk(layout string) (prefix string, std int, suffix string)

return layout[0:i], stdday, layout[i+1:]

case '_': // _2, _2006

if len(layout) >= i+2 && layout[i+1] == '2'

return layout[0:i], stdunderday, layout[i+2:]

}...}

(由於該函式行數比較多,所以只摘抄部分,如果有興趣研究,請移步 format.go 源** )

我暫時不知道 golang 為何使用這樣的格式化字串,但是既然這樣設計了,我們就應該如此使用。

golang時間格式化

golang時間處理 相關包 time 當前時間戳 fmt.println time.now unix 1389058332當前格式化時間 fmt.println time.now format 2006 01 02 15 04 05 這是個奇葩,必須是這個時間點,據說是go誕生之日,記憶方法 6 ...

golang之路 時間格式化

有人問了問go的時間格式化問題,於是乎自己嘗試了下,發現巨坑爹,不按常理出牌啊 format的竟然模版必須如下面的每個數字,t time.unix 1362984425,0 nt t.format 2006 01 02 15 04 05 fmt.println nt 附上現有的go格式 const ...

golang 時間格式化總結

通過date.now方法獲取的是基於當地時區的時間 now date.now 結果是2019 06 27 10 28 31.282649389 0800 cst m 0.000347190,注意是帶了當地時區 08的 通過time.parse將字串轉化為時間型別,是utc時間 before,time...