2
1

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 3 years have passed since last update.

Railsで時刻だけを比較する方法(何時〜何時までの間は、みたいなやつ)

Posted at

問題の背景

深夜営業で23時〜翌5時までは15%増し、みたいなやつをどう書くか?という話。
「23時〜翌5時」という条件を上手く判定したい。

解決方法

Time型で比較しようとすると日付情報まで入ってきて面倒くさいので、strftimeto_iで時刻部分だけ数値化してあげてから比較すれば良い。

def late_time?(time)
  num = time.strftime('%H%M').to_i
  [*0..459, *2300..2359].include?(num)
end

target_time = Time.zone.parse('2020/9/1 23:00')
p late_time?(target_time) #=> true

target_time = Time.zone.parse('2020/9/2 0:00')
p late_time?(target_time) #=> true

target_time = Time.zone.parse('2020/9/2 4:59')
p late_time?(target_time) #=> true

target_time = Time.zone.parse('2020/9/2 5:00')
p late_time?(target_time) #=> false

target_time = Time.zone.parse('2020/9/2 6:00')
p late_time?(target_time) #=> false

target_time = Time.zone.parse('2020/9/2 22:59')
p late_time?(target_time) #=> false
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?