Priyanshu0007
Priyanshu0007

Reputation: 23

Convert datetime to time object in ruby on rails

I have a time like

"estimatedTime": "2022-11-09T22:59:00Z"

as json, which is parsed into datetime and saved in the db (t.datetime "estimated_time").

I want to find the difference between this estimated time and the current time in hours.

Currently i am getting the current time using

Time.now.utc

which is giving me the current time as Time object.

Please suggest on how to solve this issue and find the difference between them. First i cant quite figure how the conversion from json to datetime will look like. Additionally i am also confused as to how this datetime will then to converted to time object to find the difference. I am new to rails and ruby so i am getting confused.

ruby 2.7.5p203 Rails 4.2.11

I have tried various functions but it has led to more confusion as to what should be done here.

Upvotes: 0

Views: 225

Answers (1)

max
max

Reputation: 102222

You don't need to do any conversion here. Just use the - (minus) method on Time/DateTime which gives the difference between two times in seconds as a float:

irb(main):013:0> Time.current - 1.hour.ago
=> 3599.9999717 # The rounding error is inherent to floats

This works even if other is a DateTime or ActiveSupport::TimeWithZone.

You can then use ActiveSupport::Duration to convert seconds to hours or any other unit of time:

irb(main):012:0> (Time.current - 1.day.ago).round.seconds.in_hours
=> 24.0

Rails also has a built in time_ago_in_words method to humanize times for your views.

Upvotes: 0

Related Questions