Created
July 21, 2016 07:59
-
-
Save ali-sheiba/24308aa44de457694baf0daed15cc6e3 to your computer and use it in GitHub Desktop.
Get timezone name from timezone offset like "GMT+03:00" => "Baghdad"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example get_timezone("GMT+03:00") | |
def get_timezone(offset) | |
# return false if timezone not valid | |
return false unless ActiveSupport::TimeZone.all.map(&:formatted_offset).include?(offset.gsub("GMT","")) | |
# find zone name | |
zone_name = ActiveSupport::TimeZone.all.map(&:to_s).select { |x| x.include?(offset) }.first.gsub("(#{offset}) ", "") | |
# return false if zone_name not found | |
return false unless zone_name.present? | |
# return false if zone name not valid | |
return false unless ActiveSupport::TimeZone[zone_name].present? | |
# return zone name | |
zone_name | |
end | |
# TESTES | |
## for test true in all zones | |
get_timezone("GMT+03:00") # "Baghdad" | |
get_timezone("GMT+05:30") # "Chennai" | |
ActiveSupport::TimeZone.all.map(&:formatted_offset).each { |z| get_timezone("GMT#{z}") } | |
# test for false | |
get_timezone("GMT+03:08") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment