0
0

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 1 year has passed since last update.

go言語  time.Format() time.Round() の挙動に注意

Last updated at Posted at 2022-07-06

まとめ

  • time.Round(time.Second)を使うと、時刻は四捨五入的に処理される(真ん中で切り分ける)
  • time.Format("2006-01-02 15:04:05")を使うと、秒未満は切り捨てられる

場面

SQLiteを使っていて、秒単位の時刻を記録していた。その際に想定外の値のズレが発生したため、調査していた。上記の仕様を確認した。

コード

	a := time.Date(2000, 1, 1, 1, 1, 1, 300_000_000, time.UTC)
	b := time.Date(2000, 1, 1, 1, 1, 1, 700_000_000, time.UTC)

	fmt.Printf("round a %v\n", a.Round(time.Second))//round a 2000-01-01 01:01:01 +0000 UTC
	fmt.Printf("round b %v\n", b.Round(time.Second))//round b 2000-01-01 01:01:02 +0000 UTC

	fmt.Printf("format a %v\n", a.Format("2006-01-02 15:04:05")) //format a 2000-01-01 01:01:01
	fmt.Printf("format b %v\n", b.Format("2006-01-02 15:04:05")) //format b 2000-01-01 01:01:01

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?