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.
"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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With