Golang 時間格式化的奇怪設定 —— 爲何你一直出錯

首發於:http://blog.shajiquan.com/2015/12/golang-time-format/golang

今天有人在羣裏問:code

問一個時間格式化問題:
fmt.Println(time.Now().Format("2006year 01month 02day"))
2015year 12month 18day

fmt.Println(time.Now().Format("2015year 01month 01day"))
181253year 12month 12day
爲何?
困擾很久

首先,這是一個很奇葩的問題。orm

其次,我,以及比我對 Golang 更瞭解的朋友,都掉過這個坑。咱們曾在這個問題上,花了不少時間,最後發現是 Golang 本身的奇怪設定致使。尤爲是,一段時間不用 time 包後,過段時間竟然又忘了。blog

而後,怪咱們沒看文檔,但是...文檔

結論:年、月、日、時、分、秒,英文、數字,必須精確地限定到 golang 指定的時間原點:2006-01-02 15:04:05字符串

示例:get

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("hello ")

    now := time.Now()

    nowRight := now.Format("2006-01-02 15:04")
    fmt.Println(nowRight)

    nowWrong := now.Format("2006-01-03日錯了 15:05 分錯了")
    fmt.Println(nowWrong)

    fmt.Println(now.Format("Mon Jan _2 15:04:05 2006 年"))
    fmt.Println("變態吧!")
}

附,格式化字符串模板:it

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"
)
相關文章
相關標籤/搜索