Go言語の時刻フォーマットをまずご覧ください
const (
stdLongMonth = "January"
stdMonth = "Jan"
stdNumMonth = "1"
stdZeroMonth = "01"
stdLongWeekDay = "Monday"
stdWeekDay = "Mon"
stdDay = "2"
stdUnderDay = "_2"
stdZeroDay = "02"
stdHour = "15"
stdHour12 = "3"
stdZeroHour12 = "03"
stdMinute = "4"
stdZeroMinute = "04"
stdSecond = "5"
stdZeroSecond = "05"
stdLongYear = "2006"
stdYear = "06"
stdPM = "PM"
stdpm = "pm"
stdTZ = "MST"
stdISO8601TZ = "Z0700" // prints Z for UTC
stdISO8601ColonTZ = "Z07:00" // prints Z for UTC
stdNumTZ = "-0700" // always numeric
stdNumShortTZ = "-07" // always numeric
stdNumColonTZ = "-07:00" // always numeric
)
これ別に具体例を書いているわけではないんです。
現在時刻をyyyymmdd形式で出力したかったら、
now := time.Format(time.Now(),"20060102")
と書かないといけなくて、年なら2006、月なら01、日なら02、これ以外の数字は許されません。
now := time.Format(time.Now(),"20071130")
とかは書けません。
アメリカでは月日年の順で書くので具体的で分かりやすいでしょ?ってことらしいですが…
むしろアメリカ順を採用してない国の人にとっては分かりにくいこと極まりないです。
そこで、こんなパッケージを書きます。
package timeconv
import (
"strings"
"time"
)
func Parse(layout, value string) (time.Time, error) {
return time.Parse(convert(layout), value)
}
func Format(t time.Time, expression string) string {
return t.Format(convert(expression))
}
func convert(expression string) string {
res := strings.ReplaceAll(expression, "yyyy", "2006")
res = strings.ReplaceAll(res, "yy", "06")
res = strings.ReplaceAll(res, "MMMM", "January")
res = strings.ReplaceAll(res, "MMM", "Jan")
res = strings.ReplaceAll(res, "MM", "01")
res = strings.ReplaceAll(res, "M", "1")
res = strings.ReplaceAll(res, "dddd", "Monday")
res = strings.ReplaceAll(res, "ddd", "Mon")
res = strings.ReplaceAll(res, "dd", "02")
res = strings.ReplaceAll(res, "d", "2")
res = strings.ReplaceAll(res, "HH", "15")
res = strings.ReplaceAll(res, "hh", "03")
res = strings.ReplaceAll(res, "h", "3")
res = strings.ReplaceAll(res, "mm", "04")
res = strings.ReplaceAll(res, "m", "4")
res = strings.ReplaceAll(res, "ss", "05")
res = strings.ReplaceAll(res, "s", "5")
res = strings.ReplaceAll(res, "Ztttt", "Z0700")
res = strings.ReplaceAll(res, "Ztt:tt", "Z07:00")
res = strings.ReplaceAll(res, "-tttt", "-0700")
res = strings.ReplaceAll(res, "-tt", "-07")
res = strings.ReplaceAll(res, "-tt:tt", "-07:00")
res = strings.ReplaceAll(res, "+tttt", "-0700")
res = strings.ReplaceAll(res, "+tt", "-07")
res = strings.ReplaceAll(res, "+tt:tt", "-07:00")
return res
}
自分はVB系言語に慣れているのでVBっぽく書けるように改良してみました。
文字を置き換えるだけの簡単な仕組みですがこれだけでずいぶん快適になりました。
date := time.Format(time.Now(),"2006年01月02日") // 2021年10月19日
// ↓
date = timeconv.Format(time.Now(),"yyyy年MM月dd日") // 2021年10月19日
now := time.Format(time.Now(),"15:04:05") // 22:36:15
// ↓
now = timeconv.Format(time.Now(),"HH:mm:ss") // 22:36:15