Skip to content

Instantly share code, notes, and snippets.

@ali-sheiba
Created July 21, 2016 07:59
Show Gist options
  • Save ali-sheiba/24308aa44de457694baf0daed15cc6e3 to your computer and use it in GitHub Desktop.
Save ali-sheiba/24308aa44de457694baf0daed15cc6e3 to your computer and use it in GitHub Desktop.
Get timezone name from timezone offset like "GMT+03:00" => "Baghdad"
# 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