Reputation: 23
I needed to know how many hours were in a Daylight Savings Day and ended up with this:
>(Time.zone.parse('31-10-2021').end_of_day - Time.zone.parse('31-10-2021').beginning_of_day)/3600
=> 24.99999999999972
Is there a Rails-ier way? something like Date.parse('31-10-2021').hours
or Date.parse('31-10-2021').hours_in_day
?
Upvotes: 0
Views: 181
Reputation: 102174
If you're using Rails 6.1 you can use ActiveSupport::Duration#in_hours:
hours = Time.zone.new(2021, 10, 31).then do |day|
(day.beginning_of_day-day.end_of_day).in_hours
.round.to_i # optional
end
In older versions of Rails you can do:
hours = Time.zone.new(2021, 10, 31).then do |day|
((day.beginning_of_day-day.end_of_day) / 1.hour).round.to_i
end
Upvotes: 2