I have the time of this format "20:10 PM", I need to find the difference between Time.now
with the given time
For example If Time.now
says 2022-05-17 18:32:52.133290553 -0700
, I need to find the difference between Time.now
and "20:10 PM" for same-day today.
I am not able to find any references on Ruby on Rails for that.
CodePudding user response:
Assuming you always want to compare Time.now
with a time from today (i.e 20:30 for today), you could construct a new Time
instance for the time you're comparing.
todays_year = Time.now.year
todays_month = Time.now.month
todays_day = Time.now.day
time_to_compare = Time.new(todays_year, todays_month, todays_day, 20, 30) # 20 and 30 represent the dynamic time you want to compare
time_diff = ((Time.now - time_to_compare) / 3600).round(2) # assuming you want to know the difference in hours and rounded to 2 decimal places
CodePudding user response:
Very simple way:
>> Time.now - Time.parse("20:10 PM")
=> 10995.706874
Time.parse
will assume today's date if it is not given a date. Returned result is in seconds.