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.
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.
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", ...}
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.
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.
try this Time.now.getlocal.zone
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With