开发者

How can I use Ruby to parse a time as though it is in a time zone I specify, with zone in the format America/Los_Angeles?

开发者 https://www.devze.com 2023-03-19 03:46 出处:网络
I want to be able to parse a Time from a string in Ruby (1.8.7), where the string does not contain any time zone information.I would like to treat the string as though it were in any of a number of ti

I want to be able to parse a Time from a string in Ruby (1.8.7), where the string does not contain any time zone information. I would like to treat the string as though it were in any of a number of time zones specified in this type of format: 'America/New_York'.

Time string example:

'2010-02-05 01:00:01'

I have spent quite a while trying to figure this one out.

I did find a similar question, but its answer does not apply in my case: How do I get Ruby to parse time as if it were in a different time zone?

The problem with the abov开发者_运维问答e solution is that my time zones cannot all be represented in the 3-letter format supported by Time.parse (http://www.ruby-doc.org/stdlib-1.8.7/libdoc/time/rdoc/classes/Time.html#M004931).

Is there a good way to accomplish what I'm trying to do here?

Edit: Made my answer actually appear as an answer.


require 'active_support/all'
time = ActiveSupport::TimeZone.new('UTC').parse('2010-02-05 01:00:01')

puts time
puts time.in_time_zone('EST')


Here's what I came up with using the tzinfo gem as suggested, though it seems rather complicated and unintuitive to me. As an end result I get the time parsed as though it were in the time zone I wanted, though represented by a Time object in UTC. I can also display it in the time zone I want using tzinfo's strftime:

jruby-1.6.1 :003 > time = '2010-05-01 01:00:00'
 => "2010-05-01 01:00:00" 
jruby-1.6.1 :004 > tz = TZInfo::Timezone.get('America/New_York')
 => #<TZInfo::DataTimezone: America/New_York> 
jruby-1.6.1 :005 > time += ' UTC'
 => "2010-05-01 01:00:00 UTC" 
jruby-1.6.1 :006 > time = Time.parse(time)
 => Sat May 01 01:00:00 UTC 2010 
jruby-1.6.1 :007 > time = tz.local_to_utc(time)
 => Sat May 01 05:00:00 UTC 2010 
jruby-1.6.1 :010 > tz.strftime('%Y-%m-%d %H:%M:%S %Z', time)
 => "2010-05-01 01:00:00 EDT" 

I believe this will suit my needs, but I wonder if I can get the Time to actually be in the timezone above (instead of just UTC).


You have two options the way I see it. On the one hand you could map the format you wish to use in an array (or any other structure you wish) to the 3-letter format used by Time.parse.

The other option is using the tzinfo gem as specified by my which seems to do the job quite nicely.

>> tz = TZInfo::Timezone.get("America/New_York")
=> #<TZInfo::DataTimezone: America/New_York>
>> tz.now
=> Thu Jul 07 16:29:13 UTC 2011
>> tz = TZInfo::Timezone.get("Europe/Rome")
=> #<TZInfo::DataTimezone: Europe/Rome>
>> tz.now
=> Thu Jul 07 22:30:03 UTC 2011
0

精彩评论

暂无评论...
验证码 换一张
取 消