LoginSignup
5

More than 3 years have passed since last update.

golangのtime.Timeの当日00:00:00を取得する方法とベンチマーク

Last updated at Posted at 2016-01-20

その日の00:00:00を取得したい場合、ありますよね。

例:2015-10-20 12:12:34 --> 2015-10-20 00:00:00

こんな変換です。

各プログラム

使用しているコードをushios/benchmark-go-zerodateに公開しました。

文字列にいちど変換する奴(BenchmarkZeroHourUsingFmt)

now := time.Now()
st := fmt.Sprintf("%s 00:00:00 %s", now.Format("2006-01-02"), now.Format("-0700"))
day, _ := time.Parse("2006-01-02 15:04:05 -0700", st)

fmt.Println(day)

ちゃんと計算する奴(BenchmarkZeroHourUsingFormat)

now := time.Now()
nanosecond := time.Duration(now.Nanosecond())
second := time.Duration(now.Second())
minute := time.Duration(now.Minute())
hour := time.Duration(now.Hour())
dur := -1 * (nanosecond + second*time.Second + minute*time.Minute + hour*time.Hour)
day := now.Add(dur)

fmt.Println(day)

@heliac2000 さんのコメントから(BenchmarkZeroHourUsingAdd)

他の処理と合わせるために、time.Time型に変換処理を追加しています。

now := time.Now()
st := time.Now().Format("2006-01-02 00:00:00 -0700 MST")
day, _ := time.Parse("2006-01-02 15:04:05 -0700 MST", st)

fmt.Println(day)

@spiegel-im-spiegel さんのコメントから(BenchmarkZerHourUnixTime)

コメントをいただきまして、こちらの方法だと、タイムゾーンの問題でズレが発生するそうで、https://qiita.com/go_sagawa/items/836398020100df486184 の記事をご覧いただけたほうが良さそうです。

now := time.Now()
ut := now.Unix()
_, offset := now.Zone()
day := time.Unix((ut/86400)*86400-int64(offset), 0)

fmt.Println(day)

ベンチマーク結果

BenchmarkZeroHourUsingFmt-8      1000000          1410 ns/op
BenchmarkZeroHourUsingFormat-8   1000000          1093 ns/op
BenchmarkZeroHourUsingAdd-8     10000000           169 ns/op
BenchmarkZerHourUnixTime-8      10000000           120 ns/op

@spiegel-im-spiegel さんのUNIXタイムで計算する方法が早そうです。

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
What you can do with signing up
5