覚えたら書く

IT関係のデベロッパとして日々覚えたことを書き残したいです。twitter: @yyoshikaw

Go言語 - 日時のフォーマット処理

本エントリでは、Go言語で日時を特定の書式にフォーマットする処理を実行してみます。

基本的にはtimeパッケージのTime.Format関数を利用することになります。


例えばJavaなら、LocalDateTime#format やら SimpleDateFormat#format 等を利用してフォーマットを行いますが、
その時に与える書式は例えばyyyy/MM/dd HH:mm:ssという文字列になります。

で、これと同じことをGoでやろうとした場合、指定する書式は

2006/01/02 15:04:05

です。具体的な上記の日時を書式として与える必要があります。

慣れの問題なんでしょうけど、具体的な値を指定するというのは私には違和感がありました。

一応典型的な書式はtimeパッケージでconstとして提供されています。(が、日本人好みのスラッシュが入った書式は無いです・・)

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"
)

ちなみに、与えられる日時は上記の値(2006年1月2日 15:04:05)に固定されていて、例えば年部分を 2017 にしたり、月部分を 12 にしたり とかはできません。(やると結果がおかしなことになります)

ただし、12時間表記にするために時間部分の 15 を 03 にしたり、 ゼロ埋めしないように 秒部分の 05 を 5 にしたり等はOKです。


以下で現在日時を色々な書式でフォーマットして出力してみました。

■サンプルコード

package main

import (
    "fmt"
    "time"
)

func main() {
    nowTime := time.Now()

    const format1 = "2006/01/02 15:04:05" // 24h表現、0埋めあり
    fmt.Printf("now -> %s\n", nowTime.Format(format1))

    const format2 = "2006/1/2 3:4:5" // 12h表現、0埋め無し
    fmt.Printf("now -> %s\n", nowTime.Format(format2))

    const DateFormat = "2006/01/02"
    const TimeFormat = "15:04:05"
    const MilliFormat = "2006/01/02 15:04:05.000"
    const MicroFormat = "2006/01/02 15:04:05.000000"
    const NanoFormat = "2006/01/02 15:04:05.000000000"

    fmt.Printf("yyyy/MM/dd -> %s\n", nowTime.Format(DateFormat))
    fmt.Printf("HH:mm:ss   -> %s\n", nowTime.Format(TimeFormat))

    // ミリ秒まで出力
    fmt.Printf("Milli -> %s\n", nowTime.Format(MilliFormat))

    // マイクロ秒まで出力
    fmt.Printf("Micro -> %s\n", nowTime.Format(MicroFormat))

    // ナノ秒まで出力
    fmt.Printf("Nano  -> %s\n", nowTime.Format(NanoFormat))

    // Unixtimeに変換
    unixTime := nowTime.Unix()
    fmt.Printf("unixTime -> %d\n", unixTime)
}


■実行結果

now -> 2017/05/24 19:21:04
now -> 2017/5/24 7:21:4
yyyy/MM/dd -> 2017/05/24
HH:mm:ss   -> 19:21:04
Milli -> 2017/05/24 19:21:04.135
Micro -> 2017/05/24 19:21:04.135562
Nano  -> 2017/05/24 19:21:04.135562200
unixTime -> 1495621264


というわけで無事に日時のフォーマット処理ができました。(2006/01/02 15:04:05を頭に入れとこう。)



関連記事