Reputation: 63667
In Rails, how can I calculate the time until 10am the next day, and report it in hours and minutes?
For example, if it was 11:30pm, I would get "10 hours 30 minutes"?
Things I'm trying:
// Get the right day
if (**before 10am**)
days = Time.now
else
days = Time.now + 1.days
//
Upvotes: 0
Views: 2139
Reputation: 477
Try creating a time variable. The following is not neat but is workable.
tomorrow_10_am = Time.new((Date.today + 1).year,
(Date.today + 1).month,
(Date.today + 1).day,
10
)
time_calculation = ((tomorrow_10_am - Time.now)/1.minute).round
result = (time_calculation / 60).to_s + " hours " + (time_calculation % 60).to_s + " minutes"
# the result is the time difference in hours and minutes format
Upvotes: 1
Reputation: 14402
You cannot get the precise format you want using just Rails (ActiveSupport + ActiveView that is) but you can get close:
time_now = Time.zone.now
time_tomorrow_at_10 = Time.zone.tomorrow.at_beginning_of_day.advance(hours: 10)
distance_of_time_in_words(time_now, time_tomorrow_at_10) # => about 24 hours
Note that the usage of Time.now
is almost always incorrect as it doesn't take your app's configured time zone into account.
Upvotes: 1
Reputation: 1230
Rails doesn't have precise helper for that. If you use distance_of_time_in_words(from_time, to_time)
, it will return rough estimation:
distance_of_time_in_words(Time.now, Date.tomorrow + 10.hours)
#=> "1 day"
So you can use this gem to get really precise time.
time_ago_in_words(Date.tomorrow + 10.hours)
#=> "22 hours, and 30 minutes"
Upvotes: 0