3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【メモ】Goで `blog-YYYYMMDD.md` のような感じで time.Time を Format する

3
Posted at

背景

今更ながら、time - The Go Programming Languageを読んでいたら、Time.Format を以下のようなオーソドックスな使い方以外にも便利に使えることを発見したのでメモ。

package main

import (
	"fmt"
	"time"
)

func main() {
	t := time.Date(2019, 9, 5, 0, 0, 0, 0, time.Local)
	fmt.Println(t.Format("2006/01/02"))
	fmt.Println(t.Format(time.RFC1123))
}

Time.Format で指定するレイアウトについて

These are predefined layouts for use in Time.Format and time.Parse. The reference time used in the layouts is the specific time:

Mon Jan 2 15:04:05 MST 2006

【意訳】
Time.Format と time.Parse で使用するための事前に定義されたレイアウトが存在する。レイアウトで使用される参照時間は、具体的な時間。

Mon Jan 2 15:04:05 MST 2006

To define your own format, write down what the reference time would look like formatted your way

【意訳】自身でフォーマットを定義するには、参照時間がどのようにフォーマットされるかを書く。

引用元: time - The Go Programming Language

より具体的な使用方法は、time - The Go Programming Languageを参照されたいが、仕様に沿っていれば、結構柔軟にフォーマットを定義することができる。

実際にやってみた

実装例

package main

import (
	"fmt"
	"time"
)

func main() {
	t := time.Date(2019, 9, 5, 0, 0, 0, 0, time.Local)
	fmt.Println(t.Format("blog-20060102.md"))
}

実行結果

blog-20190905.md

ダメな実装例

以下のようにすると、レイアウトが不正( 20050102 )なので、うまくフォーマットできない

package main

import (
	"fmt"
	"time"
)

func main() {
	t := time.Date(2019, 9, 5, 0, 0, 0, 0, time.Local)
	fmt.Println(t.Format("blog-20050102.md"))
}

実行結果

blog-50000905.md

参考

time - The Go Programming Language

3
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?