Go言語(golang)のタイムフォーマット
golangで時刻をフォーマット(文字列化)するには Mon Jan 2 15:04:05 MST 2006
を使います。
他の言語のように %a %b %d %X %Z %Y
ではありません。なので %Y
は 2006
です。
このGo言語のフォーマットは、stack overflowの回答にあるように、
月、日、時、分、秒、年、タイムゾーン の順で 1 2 3 4 5 6 7 になっているそうです。
基本的な使い方
time.Time 型に Format 関数があるので、その引数にレイアウトの文字列を指定します。
package main import "time" func main() { s = time.Now().Format("Mon Jan 2 15:04:05 MST 2006") println(s) // Wed Oct 9 18:35:20 JST 2019 s = time.Now().Format("2006/01/02 15:04:05") println(s) // 2019/10/09 18:35:43 s = time.Now().Format("今年は 2006年です。") println(s) // 今年は 2019年です。 // 時刻をファイル名にする s = time.Now().Format("2006-0102-150405.txt") println(s) // 2019-1009-183543.txt // 定数で定義してあるフォーマットを使う s = time.Now().Format(time.RFC822) println(s) // 09 Oct 19 18:38 JST }
標準化されているフォーマットなどは、定数で定義してあります time pkg-contents。
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" )
日付や年などのフォーマットは以下の通りに定められています。format.go(LINE92)より。
const ( _ = iota stdLongMonth = iota + stdNeedDate // "January" stdMonth // "Jan" stdNumMonth // "1" stdZeroMonth // "01" stdLongWeekDay // "Monday" stdWeekDay // "Mon" stdDay // "2" stdUnderDay // "_2" stdZeroDay // "02" stdUnderYearDay // "__2" stdZeroYearDay // "002" stdHour = iota + stdNeedClock // "15" stdHour12 // "3" stdZeroHour12 // "03" stdMinute // "4" stdZeroMinute // "04" stdSecond // "5" stdZeroSecond // "05" stdLongYear = iota + stdNeedDate // "2006" stdYear // "06" stdPM = iota + stdNeedClock // "PM" stdpm // "pm" stdTZ = iota // "MST" stdISO8601TZ // "Z0700" // prints Z for UTC stdISO8601SecondsTZ // "Z070000" stdISO8601ShortTZ // "Z07" stdISO8601ColonTZ // "Z07:00" // prints Z for UTC stdISO8601ColonSecondsTZ // "Z07:00:00" stdNumTZ // "-0700" // always numeric stdNumSecondsTz // "-070000" stdNumShortTZ // "-07" // always numeric stdNumColonTZ // "-07:00" // always numeric stdNumColonSecondsTZ // "-07:00:00" stdFracSecond0 // ".0", ".00", ... , trailing zeros included stdFracSecond9 // ".9", ".99", ..., trailing zeros omitted stdNeedDate = 1 << 8 // need month, day, year stdNeedClock = 2 << 8 // need hour, minute, second stdArgShift = 16 // extra argument in high bits, above low stdArgShift stdMask = 1<<stdArgShift - 1 // mask out argument )