Local Time Zone in Ruby

2019-04-20 08:45发布

Needs to create a Rails App where I want to get the time in local time Zone i.e. if the location is Delhi the time zone should be IST and if the the location is San Fransisco the time zone should be PDT.

How to accomplish this in ruby on rails?

P.S. One line code that can set the time zone automatically according to the location.

2条回答
Explosion°爆炸
2楼-- · 2019-04-20 09:03

If you need the Olson time zone (because three-letter time zones are ambiguous, as are GMT offsets), it looks like there's no way to do it in pure Ruby/Rails. Ruby will only provide the short code (basically via date +%Z), and Rails uses the time zone of its configuration (default: UTC).

That said, shelling out can be made to work in combination with 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
查看更多
【Aperson】
3楼-- · 2019-04-20 09:06

try this Time.now.getlocal.zone

查看更多
登录 后发表回答