如何使用 Ruby 来解析时间,就好像它位于我指定的时区中一样,时区格式为 America/Los_Angeles?
我希望能够从 Ruby (1.8.7) 中的字符串解析时间,其中该字符串不包含任何时区信息。我想将该字符串视为位于以这种格式指定的多个时区中的任何一个中:“America/New_York”。
时间字符串示例:
'2010-02-05 01:00:01'
我花了相当长的时间试图弄清楚这个问题。
我确实找到了类似的问题,但其答案不适用于我的情况: 我如何让 Ruby 解析时间,就好像它在不同的时区一样?
上述解决方案的问题是我的时区不能全部表示在Time.parse 支持的 3 字母格式 (http://www.ruby-doc.org/stdlib-1.8.7/libdoc/time/rdoc/classes/Time.html#M004931)。
有没有好的方法来完成我在这里想做的事情?
编辑:使我的答案实际上显示为答案。
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 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?
Edit: Made my answer actually appear as an answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是我按照建议使用 tzinfo gem 想到的,尽管它对我来说似乎相当复杂且不直观。作为最终结果,我得到的时间被解析为就像在我想要的时区中一样,尽管由 UTC 中的 Time 对象表示。我还可以使用 tzinfo 的 strftime 在我想要的时区中显示它:
我相信这会满足我的需求,但我想知道我是否可以让时间实际上位于上面的时区(而不仅仅是 UTC)。
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:
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).
在我看来,你有两个选择。一方面,您可以将您希望在数组(或您希望的任何其他结构)中使用的格式映射到 Time.parse 使用的 3 字母格式。
另一个选项是使用我指定的 tzinfo gem,这似乎可以很好地完成这项工作。
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.