我如何使用 Ruby 解析时间,就好像它在我指定的时区中一样,时区的格式为 America/Los_Angeles? [英] 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?

查看:30
本文介绍了我如何使用 Ruby 解析时间,就好像它在我指定的时区中一样,时区的格式为 America/Los_Angeles?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从 Ruby (1.8.7) 中的字符串解析时间,其中该字符串不包含任何时区信息.我想将字符串视为位于以此类格式指定的多个时区中的任何一个中:'America/New_York'.

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'.

时间字符串示例:

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

我花了很长时间试图解决这个问题.

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

我确实找到了一个类似的问题,但它的答案不适用于我的情况:我如何让 Ruby 解析时间,就像它在不同的时区一样?

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?

上述解决方案的问题是我的时区不能全部用Time.parse支持的3个字母格式表示(http://www.ruby-doc.org/stdlib-1.8.7/libdoc/time/rdoc/classes/时间.html#M004931).

The problem with the above 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?

使我的答案实际上显示为答案.

Made my answer actually appear as an answer.

推荐答案

以下是我按照建议使用 tzinfo gem 的想法,尽管它对我来说似乎相当复杂和不直观.作为最终结果,我将时间解析为好像在我想要的时区中一样,尽管由 UTC 中的 Time 对象表示.我也可以使用 tzinfo 的 strftime 在我想要的时区显示它:

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" 

我相信这将满足我的需求,但我想知道我是否可以让时间实际位于上面的时区(而不仅仅是 UTC).

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).

这篇关于我如何使用 Ruby 解析时间,就好像它在我指定的时区中一样,时区的格式为 America/Los_Angeles?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆