Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Time Zone in Ruby

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.

like image 517
Swati Aggarwal Avatar asked Sep 16 '12 08:09

Swati Aggarwal


People also ask

How do I get local time in Ruby?

Ruby | Time localtime() function Time#localtime() : localtime() is a Time class method which returns local time (using the local time zone in effect at the creation time of time) by time conversion using modification in the receiver.

How do I change the TimeZone in Ruby?

updated answer: use ActiveSupport PS: if you want to see all of the time zone names supported, you can refer to: >> ActiveSupport::TimeZone::MAPPING => => {"International Date Line West"=>"Pacific/Midway", "Midway Island"=>"Pacific/Midway", ...}

How do I get UTC time in Ruby?

Time Zones You can check the current time zone for a Time object using the zone method. This will give you the time zone abbreviation. If you want the time zone offset you can use the utc_offset method. The output for this method is in seconds, but you can divide by 3600 to get it in hours.

How do I find time zones in rails?

In Rails, to see all the available time zones, run: $ rake time:zones:all * UTC -11:00 * American Samoa International Date Line West Midway Island Samoa * UTC -10:00 * Hawaii * UTC -09:00 * Alaska ... The default time zone in Rails is UTC.


2 Answers

try this Time.now.getlocal.zone

like image 183
suvankar Avatar answered Oct 10 '22 22:10

suvankar


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
like image 24
numist Avatar answered Oct 10 '22 23:10

numist