Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a time string to a specific timezone?

I've this string:

Sunday, Oct 7 4:00pm

When I use Time.parse, Ruby assumes the timezone is UTC. How do I tell Ruby to give me -0700 timezone? I've tried using

tz.utc_to_local(Time.parse(string))

but I still get the UTC +0000 time zone back.

like image 719
sent-hil Avatar asked Nov 12 '22 21:11

sent-hil


1 Answers

"When parsing time information it’s important to never do it without specifying the time zone."

That gem of an advice is from this useful blogpost : Working with time zones in Ruby on Rails.

Irrespective of whether you are using rails or not, the time string always has a timezone attached to it. In your case, you are assuming that the time string has a -0700 offset, but not passing the timezone information to the parse method (which is assuming it is UTC).

> Rails.application.config.time_zone
=> "Mountain Time (US & Canada)"

This is because I have the following config:

config.time_zone = 'Mountain Time (US & Canada)'

> string = "Sunday, Oct 7 4:00pm"
=> "Sunday, Oct 7 4:00pm"
> Time.parse(string)
=> 2012-10-07 16:00:00 -0600
> Time.parse(string).zone
=> "MDT"

Works the same way in pure ruby as well:

> require 'time'
=> true
> Time.local( 2012, 10, 07 )
=> 2012-10-07 00:00:00 -0600
> Time.local( 2012, 10, 07 ).zone
=> "MDT" 
> string = "Sunday, Oct 7 4:00pm"
=> "Sunday, Oct 7 4:00pm"
> Time.parse(string)
=> 2012-10-07 16:00:00 -0600
> Time.parse(string).zone
=> "MDT"
like image 66
Prakash Murthy Avatar answered Dec 29 '22 05:12

Prakash Murthy