Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

utc_to_local returning UTC identifier #26

Closed
amritk opened this issue Sep 23, 2014 · 3 comments
Closed

utc_to_local returning UTC identifier #26

amritk opened this issue Sep 23, 2014 · 3 comments
Labels

Comments

@amritk
Copy link

@amritk amritk commented Sep 23, 2014

I'm using utc_to_local to convert a time in UTC to "America/Vancouver"

The time is correct, however it still displays +0 UTC at the end. How do I get this to display the correct UTC offset?

>> start_time
=> Thu, 25 Sep 2014 18:30:00 UTC +00:00
>> tz = TZInfo::Timezone.get("America/Vancouver")
=> #<TZInfo::DataTimezone: America/Vancouver>
>> tz.utc_to_local(start_time)
=> Thu, 25 Sep 2014 11:30:00 UTC +00:00 
>> 

Running rails 2.3.18 and Ruby 1.8.7

@amritk
Copy link
Author

@amritk amritk commented Sep 23, 2014

I know that its because my default timezone is set to UTC. But how do I get tzinfo to spit out the time with the offset for the timezone I entered?

@philr
Copy link
Member

@philr philr commented Sep 23, 2014

Ruby Time instances only support UTC offsets of zero and the offset of your local time zone. TZInfo's utc_to_local method therefore always returns results with a zero UTC offset.

If you are just interested in finding the UTC offset at a given time, you can use the period_for_utc method:

>> start_time = Time.utc(2014,9,25,18,30)
=> Thu Sep 25 18:30:00 UTC 2014
>> tz = TZInfo::Timezone.get('America/Vancouver')
=> #<TZInfo::DataTimezone: America/Vancouver>
>> tz.period_for_utc(start_time).utc_total_offset
=> -25200

Since you are using Rails, you could also use the in_time_zone method that ActiveSupport adds to the Time class.

>> start_time = Time.utc(2014,9,25,18,30)
=> Thu Sep 25 18:30:00 UTC 2014
>> start_time.in_time_zone('America/Vancouver')
=> Thu, 25 Sep 2014 11:30:00 PDT -07:00

Note that this returns an instance of ActiveSupport::TimeWithZone instead of Time.

ActiveSupport uses TZInfo internally for handling time zones.

@philr philr added the question label Sep 23, 2014
@philr philr closed this Sep 23, 2014
@pedrocarmona
Copy link

@pedrocarmona pedrocarmona commented Jul 27, 2017

To complete philr answer, without rails:

time = Time.utc(2014,9,25,18,30)
utc_total_offset = timezone.period_for_utc(time).utc_total_offset
time.getlocal(utc_total_offset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.