Ruby-on-rails 在 Rails 中,如何以可与 ActiveSupport::TimeZone[zone].parse() 一起使用的格式获取当前时区 (Time.zone)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13887643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Rails, how get current time zone (Time.zone) in a format that can be used with ActiveSupport::TimeZone[zone].parse()?
提问by jpw
How can a method take the current Time.zone and put it into a format that is usable by ActiveSupport::TimeZone[some_zone].parse()?
方法如何获取当前 Time.zone 并将其转换为可供 . 使用的格式ActiveSupport::TimeZone[some_zone].parse()?
It seems very strange that Time.zone.to_s returns a string that can not be used with ActiveSupport::TimeZone[zone].parse()
Time.zone.to_s 返回一个不能用的字符串似乎很奇怪 ActiveSupport::TimeZone[zone].parse()
Time.zone.to_sreturns "(GMT-08:00) Pacific Time (US & Canada)"
Time.zone.to_s回报 "(GMT-08:00) Pacific Time (US & Canada)"
But ActiveSupport::TimeZone["(GMT-08:00) Pacific Time (US & Canada)"]is nil.
但是ActiveSupport::TimeZone["(GMT-08:00) Pacific Time (US & Canada)"]是nil。
ActiveSupport::TimeZone["(GMT-08:00) Pacific Time (US & Canada)"]
=> nil
ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
=> (GMT-08:00) Pacific Time (US & Canada)
回答by deefour
Use Time.zone.name, not Time.zone.to_s
使用Time.zone.name,不Time.zone.to_s
[1] pry(main)> Time.zone.to_s
=> "(GMT-05:00) Eastern Time (US & Canada)"
[2] pry(main)> Time.zone.name
=> "Eastern Time (US & Canada)"
[3] pry(main)> ActiveSupport::TimeZone[Time.zone.name]
=> (GMT-05:00) Eastern Time (US & Canada)
As for how I got this (as requested), I just know the namemethod exists on Time.zone. If I didn't know this by heart though, I will check the docs. If it's not in there as you say (and it is, here), I typically inspect the class/module/object with Pry. Pry is an alternative to irb that lets me do something like
至于我是如何得到这个的(根据要求),我只知道该name方法存在于Time.zone. 如果我不知道这一点,我会检查文档。如果它不像你说的那样在那里(它是,在这里),我通常用Pry检查类/模块/对象。Pry 是 irb 的替代品,它让我可以做类似的事情
[1] pry(main)> cd Time.zone
[2] pry(#<ActiveSupport::TimeZone>):1> ls -m
Comparable#methods: < <= == > >= between?
ActiveSupport::TimeZone#methods: <=> =~ at formatted_offset local local_to_utc name now parse period_for_local period_for_utc to_s today tzinfo utc_offset utc_to_local
self.methods: __pry__
[3] pry(#<ActiveSupport::TimeZone>):1> name
=> "Eastern Time (US & Canada)"
ls -mon line [2]above prints methods on the object (if you scroll right you'll see namelisted there). You can see in [3]I can call namedirectly on the Time.zoneobject I'm inside of and get the output you're looking for.
ls -m在[2]上面的线上打印对象上的方法(如果向右滚动,您将看到name那里列出)。你可以看到[3]I canname直接调用我所在的Time.zone对象并获得你正在寻找的输出。

