Question

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?

Was it helpful?

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

OTHER TIPS

The time doesn't change, it's just adjusted to a different time zone:

a = Time.now    #=> 2013-09-27 16:01:51 +0200
b = a.dup.utc   #=> 2013-09-27 14:01:51 UTC

a == b          #=> true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top