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.

【Ruby】between?でtime.zoneを範囲指定として渡す際の注意点

Last updated at Posted at 2024-06-25

Rubyのbetween?()の返り値が想定と違かった原因をメモ。

now = Time.zone.now
start_time = Time.zone.parse("2024/07/01 12:00")
end_time = Time.zone.parse("2024/07/31 23:59")

if now.between?(start_time, end_time)
  ~...
end

データとしてはこんな感じ。
now2024/07/31 23:59になったと仮定して動作を確認していたら
条件がfalseになってif文に入らなかった。

原因

end_timeをparseしたときに秒数を指定していないので、
now23:59:00以降になると分岐条件がfalseになってif文に入らない。

解決策

終了時刻は秒数を指定する。

end_time = Time.zone.parse("2024/07/31 23:59")

end_time = Time.zone.parse("2024/07/31 23:59:59")

文章にするとそうだよねってなるのに、
いざ直面すると焦って思い出せなかった・・・orz

加筆

コメントでご教示いただいたもの。ありがとうございました。

指定の年月の月の全範囲を取得する

■ all_month

all_month
start_time = Time.zone.parse("2024/07/01")
month = start_time.all_month # → 2024/07/01 00:00 ~ 2024/07/31 23:59
month.cover?(Time.current) # → true

all_monthメソッドはstart_timeに時間を指定したtime型の値が入っていても月の最初の日付の00:00になることに注意。

指定の年月の最終日時を取得する

■ end_of_month

end_of_month
start_time = Time.zone.parse("2024/07/01")
end_time = start_time.end_of_month # → 2024/07/31 23:59
Time.current.between?(start_time, end_time) # → true

今回の事象の場合はend_of_monthを使用すると私みたいな人は書き忘れが防げそう。

0
0
2

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?