16
16

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.

時差分かりにくいよー助けてActiveSupport!

Posted at

注:ActiveSupport::TimeWithZoneとかの話じゃないです。

JSTの端末使ってる前提で。
Ruby 1.9.3p125
Rails 3.2.5

UNIX時間はどこでも同じだ

Time.now.utc
#=> 2012-08-02 06:44:35 UTC
Time.now
#=> 2012-08-02 15:44:36 +0900

Time.now.utc.to_i
#=> 1343889882
Time.now.to_i
#=> 1343889885

これ時々混乱するけど、
起点となるのはUTCの1970-01-01 00:00:00 UTCだから、
その時点では日本は1970-01-01 09:00:00 +900なわけで、
UNIX時間は同じ。

今日はいつ?

railsのActiveSupportは便利です。

rails console
Time.now.utc.beginning_of_day
#=>2012-08-02 00:00:00 UTC

Time.now.beginning_of_day
#=>2012-08-02 00:00:00 +0900

ここまではOKでしょう

Time.now.utc.beginning_of_day
#=>1343865600

Time.now.beginning_of_day
#=>1343833200

# UTC's beginning_of_day == JST's beginning_of_day + 9.hours
Time.now.utc.beginning_of_day.to_i == Time.now.beginning_of_day.to_i + 9.hours
#=> true

どうでしょ。
感覚だと逆の感じがしませんか。
JSTは9時間早いので9時間早く今日が始まっているわけです。

データストアはUTCなんだけどフロントはJST

よくあるパターンですね。

today_jst = Time.now.beginning_of_day..Time.now.end_of_day

Post.where(created_at: today_jst).count

で結局良いわけですね。

結論

こういうのは透過的にやりたいですね、ハイ。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?