Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

go-humanizeで序数や単位、日付差分を人間が読みやすい形に

go-humanizeで序数や単位、日付差分を人間が読みやすい形にできます。
以前紹介した、RailsのActive_supportのようなものです。
shuzo-kino.hateblo.jp

実際のところ

数値の切り替えサンプルは以下の通り。

package main

import (
	"fmt"
	"github.com/dustin/go-humanize"
)

func main() {
	// Result:: 83 MB.
	fmt.Printf(
		"%v MB.\n",
		humanize.Bytes(82854982),
	)

	// Result:: 79 MiB.
	fmt.Printf(
		"%v MiB.\n",
		humanize.IBytes(82854982),
	)

	// Result:: 82,854.
	fmt.Printf(
		"%v.\n",
		humanize.Comma(82854),
	)

	// Result:: 82854nd.
	fmt.Printf(
		"%v.\n",
		humanize.Ordinal(82854),
	)

}

実行結果はこんな感じに。

$ go run gohumanize.go 
83 MB MB.
79 MiB MiB.
82,854.
82854th.

日付は引数で与えたデータと現時刻の差分をとるタイプです。
こんな感じ

// time.go の 19行目

// Time formats a time into a relative string.
//
// Time(someT) -> "3 weeks ago"
func Time(then time.Time) string {
	return RelTime(then, time.Now(), "ago", "from now")
}

参考もと

godoc.org
github.com