Jon Snyder
Jon Snyder

Reputation: 2009

Rails - A better way to parse the time with a timezone?

Time.parse returns a Time object that does not have a timezone. I would like to keep the timezone information. Is there a better way to do this then the following code?

def parse_with_timezone( string_input)
  /(.*)([+-]\d\d):?(\d\d)$/.match( string_input) do |match|
    tz = ActiveSupport::TimeZone[match[2].to_i.hours + match[3].to_i.minutes]
    tz.parse( match[1])
  end
end

The input is a string like this "2012-12-25T00:00:00+09:00". This function outputs a TimeWithZone object.

Upvotes: 2

Views: 1820

Answers (3)

toxaq
toxaq

Reputation: 6838

Were you looking for a specific timezone of the current local one?

# Current zone
1.9.3p194> Time.zone.parse('2012-12-25T00:00:00+09:00')
=> Mon, 24 Dec 2012 15:00:00 UTC +00:00

Console was set at UTC for above but will work for whatever you have configured

# Specific timezone 
1.9.3p194> Time.find_zone('Wellington').parse('2012-12-25T00:00:00+09:00')
=> Tue, 25 Dec 2012 04:00:00 NZDT +13:00 

I notice you're trying to pass +9 so as an example

1.9.3p194> Time.zone = 'Tokyo'
=> "Tokyo" 
1.9.3p194> Time.zone.parse('2012-12-25T00:00:00+09:00')
=> Tue, 25 Dec 2012 00:00:00 JST +09:00

Gives you the right result.

Upvotes: 4

DGM
DGM

Reputation: 26979

I prefer to use Chronic for all my date/time parsing needs.

Upvotes: 0

Benjamin Tan Wei Hao
Benjamin Tan Wei Hao

Reputation: 9691

What about the Rails Timezone API: http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html

Upvotes: 1

Related Questions