【问题标题】:Local Time Zone in Ruby红宝石的本地时区
【发布时间】:2012-09-16 08:04:27
【问题描述】:

需要创建一个 Rails 应用程序,我想在其中获取本地时区的时间,即如果位置是 德里,则时区应该是 IST,如果位置是旧金山,时区应该是PDT

如何在 ruby​​ on rails 中实现这一点?

附:一行代码,可以根据位置自动设置时区。

【问题讨论】:

    标签: ruby-on-rails-3 timezone


    【解决方案1】:

    试试这个Time.now.getlocal.zone

    【讨论】:

    • 这给了我本地区域。我希望如果一个坐在新德里的人访问我的应用程序,那么他可以看到“IST”中的时间,如果一个人坐在 SanFransisco,他可以看到“PST”中的时间。我需要什么配置在我的应用程序中实现这一目标?
    • Time.now.zone 也有效,getlocal() 方法用于获取给定 UTC 偏移量的时间。文档:apidock.com/ruby/Time/getlocal
    【解决方案2】:

    如果您需要 Olson 时区(因为三个字母的时区不明确,GMT 偏移也是如此),看起来在纯 Ruby/Rails 中没有办法做到这一点。 Ruby 只会提供短代码(基本上通过date +%Z),Rails 使用其配置的时区(默认:UTC)。

    也就是说,shelling out can be made to workanother 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多