3
4

More than 3 years have passed since last update.

Goで日本語曜日を含む日付format

Posted at

Goに限った話じゃないけど、日本語の曜日(月, 火, 水...)を表示したいときは、先に言語公式の機能でformatしてしまい、英語の曜日を文字列置換で置き換えるとコードがきれいになる。(効率的には文字列置換は重いと思うけど、読みやすさはだいぶ上がると思う)

package main

import (
    "fmt"
    "time"
    "strings"
)

func main() {
    t := time.Now()
    weekdayja := strings.NewReplacer(
        "Sun", "日",
        "Mon", "月",
        "Tue", "火",
        "Wed", "水",
        "Thu", "木",
        "Fri", "金",
        "Sat", "土",
    )
    fmt.Println(weekdayja.Replace(t.Format("2006年1月2日(Mon曜日)")))
    // 2009年11月10日(火曜日)
}

Goで複数の文字の組を一括置換したいときは、Replacerを使うとよいようだ。
https://golang.org/pkg/strings/#NewReplacer

3
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4