在 Rails 中,如何以可与 ActiveSupport::TimeZone[zone].parse() 一起使用的格式获取当前时区 (Time.zone)? [英] In Rails, how get current time zone (Time.zone) in a format that can be used with ActiveSupport::TimeZone[zone].parse()?
问题描述
方法如何获取当前 Time.zone 并将其转换为 ActiveSupport::TimeZone[some_zone].parse()
可用的格式?
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.to_s 返回一个不能与ActiveSupport::TimeZone[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
返回 "(GMT-08:00) 太平洋时间(美国和加拿大)"
但是 ActiveSupport::TimeZone["(GMT-08:00) 太平洋时间(美国和加拿大)"]
是 nil
.
ActiveSupport::TimeZone["(GMT-08:00) Pacific Time (US & Canada)"]
=> nil
ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
=> (GMT-08:00) Pacific Time (US & Canada)
推荐答案
使用 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)
<小时>
至于我如何得到这个(根据要求),我只知道 name
方法存在于 Time.zone
上.如果我不知道这一点,我会检查文档.如果它不像你说的那样在那里(它是,这里),我通常使用 Pry 检查类/模块/对象.Pry 是 irb 的替代品,它让我可以做类似
As for how I got this (as requested), I just know the name
method 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
[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 -m
上面的 [2]
行打印对象上的方法(如果向右滚动,您将看到 name
在那里列出).您可以在 [3]
中看到我可以直接在我所在的 Time.zone
对象上调用 name
并获得输出正在寻找.
ls -m
on line [2]
above prints methods on the object (if you scroll right you'll see name
listed there). You can see in [3]
I can call name
directly on the Time.zone
object I'm inside of and get the output you're looking for.
这篇关于在 Rails 中,如何以可与 ActiveSupport::TimeZone[zone].parse() 一起使用的格式获取当前时区 (Time.zone)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!