golang 的時間格式化操做

怎麼作

簡而言之

time.Now().Format("2006-01-02 15:04:05")

你將會得到如同 yyyy-MM-dd hh-mm-ss 這樣的輸出。golang

還能夠

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 表示月份等等。code

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

你要問我爲何使用這樣看起來奇怪的格式化字符串?抱歉,我真的猜不透。對象

下面的代碼摘自golang源代碼 關於時間格式化的部分字符串

// String returns the time formatted using the format string
//  "2006-01-02 15:04:05.999999999 -0700 MST"
func (t Time) String() string {
    return t.Format("2006-01-02 15:04:05.999999999 -0700 MST")
}

能夠看到,golang中並無使用英文單詞首字母表示的格式化字符串,而是使用了一組固定的數據。get

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) {
...
        case '2': // 2006, 2
            if len(layout) >= i+4 && layout[i:i+4] == "2006" {
                return layout[0:i], stdLongYear, layout[i+4:]
            }
            return layout[0:i], stdDay, layout[i+1:]
  
        case '_': // _2, _2006
            if len(layout) >= i+2 && layout[i+1] == '2' {
                //_2006 is really a literal _, followed by stdLongYear
                if len(layout) >= i+5 && layout[i+1:i+5] == "2006" {
                    return layout[0 : i+1], stdLongYear, layout[i+5:]
                }
                return layout[0:i], stdUnderDay, layout[i+2:]
            }

...
}

(因爲該函數行數比較多,因此只摘抄部分,若是有興趣研究,請移步 format.go 源代碼 )

最後

我暫時不知道 golang 爲什麼使用這樣的格式化字符串,可是既然這樣設計了,咱們就應該如此使用。

相關文章
相關標籤/搜索