Search code examples
rubyruby-on-rails-3ruby-1.9.3

How to convert timestamp to seconds with timezone in ruby


Why ruby doesn't subtract Timezone when I convert timestamp to seconds?

1.9.3-p429 :008 > a = Time.now()
  => 2013-09-27 16:23:17 +0300 
1.9.3-p429 :011 > a.utc
  => 2013-09-27 13:23:17 UTC
1.9.3-p429 :009 > a.to_i
  => 1380288197 
1.9.3-p429 :010 > a.utc.to_i
  => 1380288197

a.to_i should be 3 hours (10800 seconds) higher than a.utc.to_i and I need it to be, how can I do it?


Solution

  • Here's the thing about Time in Ruby. Time.now.to_f gives you the number of seconds since the Epoch. More info about the Epoch is available on wikipedia

    To get a difference between two Time objects, you should just subtract them to get the difference, as noted in the docs.

    To get the difference between two of objects that hold the same time, but are of different UTC offsets (as seen in your question), simply use the utc_offset method.

    a = Time.now
    b = Time.now.utc
    
    difference = (b.utc_offset - a.utc_offset)/60/60
    #=> 5