【发布时间】:2012-09-16 08:04:27
【问题描述】:
需要创建一个 Rails 应用程序,我想在其中获取本地时区的时间,即如果位置是 德里,则时区应该是 IST,如果位置是旧金山,时区应该是PDT。
如何在 ruby on rails 中实现这一点?
附:一行代码,可以根据位置自动设置时区。
【问题讨论】:
需要创建一个 Rails 应用程序,我想在其中获取本地时区的时间,即如果位置是 德里,则时区应该是 IST,如果位置是旧金山,时区应该是PDT。
如何在 ruby on rails 中实现这一点?
附:一行代码,可以根据位置自动设置时区。
【问题讨论】:
试试这个Time.now.getlocal.zone
【讨论】:
Time.now.zone 也有效,getlocal() 方法用于获取给定 UTC 偏移量的时间。文档:apidock.com/ruby/Time/getlocal
如果您需要 Olson 时区(因为三个字母的时区不明确,GMT 偏移也是如此),看起来在纯 Ruby/Rails 中没有办法做到这一点。 Ruby 只会提供短代码(基本上通过date +%Z),Rails 使用其配置的时区(默认:UTC)。
也就是说,shelling out can be made to work 与 another answer 的组合:
def get_local_timezone_str
# Yes, this is actually a shell script…
olsontz = `if [ -f /etc/timezone ]; then
cat /etc/timezone
elif [ -h /etc/localtime ]; then
readlink /etc/localtime | sed "s/\\/usr\\/share\\/zoneinfo\\///"
else
checksum=\`md5sum /etc/localtime | cut -d' ' -f1\`
find /usr/share/zoneinfo/ -type f -exec md5sum {} \\; | grep "^$checksum" | sed "s/.*\\/usr\\/share\\/zoneinfo\\///" | head -n 1
fi`.chomp
# …and it almost certainly won't work with Windows or weird *nixes
throw "Olson time zone could not be determined" if olsontz.nil? || olsontz.empty?
return olsontz
end
【讨论】: