Struggles with Golang Date Formatting
programming
Published: 2016-05-16

This content has been moved from Qiita.

To specify date formatting in Golang, you use the time.Format function. I needed to format dates for graphite-api using the following format:

However, I encountered issues where it worked on some environments but not on others, wasting a lot of time. The problem turned out to be a bug that was fixed in a Golang version update.

Specifying the Format

Specified format: HH:SS_YYYYMMDD
So in Golang: Format("15:04_20060102")

Test Code

package main

import (
        "fmt"
        "time"
)

func main() {
        now := time.Now()
        fmt.Printf("now=%v, formatted=%s\n", now, now.Format("15:04_20060102"))
}

With Version 1.6.2

# go run main.go
now=2016-05-16 17:14:54.851096532 +0900 JST, formatted=17:14_20160516

With Version 1.5.1

# go run main.go
now=2016-05-16 17:13:45.995101638 +0900 JST, formatted=17:13160160516

It seems that the _2 part in 15:04_20060102 was being recognized as stdUnderDay.
https://github.com/golang/go/blob/master/src/time/format.go#L82

I was informed that this was fixed around version 1.6.1.
https://github.com/golang/go/commit/f4b4d2f4d9f574fe34b826bf0e6784956a247687

For now, I will update my environment to 1.6.2.