9
13

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.

Date, DateTime, Timeでの加算の違い

Posted at

rubocopでRails/TimeZoneについて怒られたのでリファクタリング。

10:42:22 - INFO - Inspecting Ruby code style: app/models/hoge.rb
Inspecting 1 file
C

Offenses:

app/models/hoge.rb:3:20: C: Rails/TimeZone: Do not use DateTime.now without zone. Use one of Time.zone.now, DateTime.current, DateTime.now.in_time_zone, DateTime.now.utc, DateTime.now.getlocal, DateTime.now.iso8601, DateTime.now.jisx0301, DateTime.now.rfc3339, DateTime.now.to_i, DateTime.now.to_f instead.
    now = DateTime.now
                   ^^^

1 file inspected, 1 offense detected

DateTime.nowTime.zone.nowに差し替えたら計算結果が違う!みたいなことになったので初歩的な内容だけどメモ。

環境

$ rbenv version
2.3.4
$ rails -v
Rails 4.2.8

検証

# Dateオブジェクトに10加算すると10日加算される
[39] pry(main)> today = Date::today
=> Tue, 18 Apr 2017
[40] pry(main)> today + 10
=> Fri, 28 Apr 2017

# DateTimeオブジェクトに10加算すると10日加算される
[41] pry(main)> now = DateTime.now
=> Tue, 18 Apr 2017 10:57:37 +0900
[42] pry(main)> now + 10
=> Fri, 28 Apr 2017 10:57:37 +0900

# Timeオブジェクトに10加算すると10秒加算される
[43] pry(main)> now = Time.zone.now
=> Tue, 18 Apr 2017 10:57:59 JST +09:00
[44] pry(main)> now + 10
=> Tue, 18 Apr 2017 10:58:09 JST +09:00

そもそもこういう、数字を直接加算するのは直感的ではないので以下のように書き換えたほうがいい。

[45] pry(main)> now = Time.zone.now
=> Tue, 18 Apr 2017 11:10:09 JST +09:00
# ちゃんとActiveSupportの機能を使う
[46] pry(main)> now + 10.days
=> Fri, 28 Apr 2017 11:10:09 JST +09:00

以上。

参考

9
13
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
9
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?