I'd like to be able to say user1 is 4 hours ahead of user2, calculated based on the time zones the users specify in their account.
Using the following code:
time1 = Time.zone.now.in_time_zone(user1.time_zone)
time2 = Time.zone.now.in_time_zone(user2.time_zone)
distance_of_time_in_words time1,time2
...gives a difference of less than a minute - similarly subtracting the two times gives 0. Rails obviously still sees these two times as the same.
Any idea how I can calculate this difference between two time zones?
start_time: 22:00 (Rails interprets this as 2015-12-31 22:00:00 +0100) second_time: 02:00 (Rails interprets this as 2015-12-31 02:00:00 +0100). The second time is 4 hours later, so in the next day.
Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.
If you take your time1 instance and call utc_offset on it, you will get the amount of time offset from UTC in seconds. Combine this with the utc_offset of time2, throw in some subtraction, and you should get the time difference in seconds. From there you can do the conversation to whatever unit of time you like.
irb(main):020:0> time1 = Time.zone.now.in_time_zone("EST")
=> Sun, 09 Jun 2013 07:11:46 EST -05:00
irb(main):021:0> time2 = Time.zone.now.in_time_zone("MST")
=> Sun, 09 Jun 2013 05:11:49 MST -07:00
irb(main):022:0> time_difference_in_seconds = time2.utc_offset - time1.utc_offset
=> -7200
irb(main):025:0> (time_difference_in_seconds/60/60).abs
=> 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With