Search code examples
ruby-on-railsrubyruby-on-rails-4activesupport

Difference between 2 timestamps(String) in hours in Rails


I have one time in a hash as

"Time": "2022-11-08T22:59:00Z"

and also i would be taking the current time in the same format using

Time.now.utc.iso8601

I want to compare these 2 times(Time-CurrentTime) to get their difference in hours. I cant quite figure out how to do that as i am new to ruby and rails. Please help me out.

ruby 2.7.5p203

Rails 4.2.11

I tried parsing them using strftime() but maybe i was doing it wrong. Please suggest.


Solution

  • It's better to compare Time object not strings. You can parse a time string using this method Time.parse. The difference will be in seconds that's why you need to divide the result by 3600

    your_hash = { "Time": "2022-11-08T22:59:00Z" } 
    (Time.now.utc - Time.parse(your_hash[:"Time"])) / 3600