LovingRails LovingRails - 5 months ago 8
Ruby Question

How to find the remaining time between two dates in a time zone in Ruby on Rails?

I am trying to do countdown for certain events using flipclock in Ruby on Rails.

I tried to find the time difference of an EST event.

time_diff = <%= (Time.utc(2016, 7, 2, 18, 14, 0).in_time_zone("Eastern Time (US & Canada)") - Time.now.in_time_zone("Eastern Time (US & Canada)")).to_i.abs %>;


I tried to check if it was correct by doing a one hour difference but I am always getting wrong number of hours left.

Answer

I think this is what you're after:

(ActiveSupport::TimeZone.new("EST").local(2016, 7, 2, 18, 14, 0) - Time.now).to_i.abs

The code in your question is equivalent to

(Time.utc(2016, 7, 2, 18, 14, 0) - Time.now).to_i.abs

You probably expect the first part of the expression to mean "18:14 EST" but it means "18:14 UTC… but show what time that was in EST".

It might clarify things if you note that

Time.utc(2016, 7, 2, 18, 14, 0).in_time_zone("EST") == Time.utc(2016, 7, 2, 18, 14, 0)

because

Time.utc(2016, 7, 2, 18, 14, 0).in_time_zone("EST").to_i == Time.utc(2016, 7, 2, 18, 14, 0).to_i

but

Time.utc(2016, 7, 2, 18, 14, 0).in_time_zone("EST").to_s != Time.utc(2016, 7, 2, 18, 14, 0).to_s