Donato
Donato

Reputation: 2777

Timezone confusion with Ruby's Time class

It's worth noting I am using Ruby 2.1.2, and so the Time class uses a signed 63 bit integer. The integer is used when it can represent a number of nanoseconds since the Epoch; otherwise, bignum or rational is used, according to the documentation.

When I use ::new without arguments, it gives me the current time using my local time zone (not UTC):

> Time.new
 => 2015-06-30 18:29:08 -0400 

It's correct. It's 6:29pm on the East coast of the US. Now I want to check the local time in two timezones to the east of EDT:

> t = Time.new(2015,6,30,18,29,8,"+02:00")
=> 2015-06-30 18:29:08 +0200 

This is where my confusion comes in. When I specify two timezones to the east of me, I expect there to be two additional hours because each timezone is 15 degrees longitude and each is represented by 1 hour.

Why did it give me the same time as my local time, instead of two hours later?

Upvotes: 2

Views: 298

Answers (1)

Makoto
Makoto

Reputation: 106430

What you think is happening isn't what's happening. What you've done is give that time an offset of GMT +2 as opposed to two hours out from your current timezone.

If you want to see the time at the offset of two hours ahead of where you are, then you want to create the instance of Time, get your local time, and shift that by the GMT offset.

Time.now.getlocal("-02:00")

If you want to compute this, you have to look at your local time's utc_offset first, then either add or subtract the product of 3600 and however many timezones you want to move. Note that this only moves timezones in whole number increments and will break in cases where a timezone that requires a different precision is needed (i.e. Newfoundland).

t = Time.now
t.getlocal(t.utc_offset + (3600 * 2))

Upvotes: 1

Related Questions