2020-12-02 10:09:37 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module TimeZoneHelper
|
2020-12-05 10:09:32 -05:00
|
|
|
TIME_ZONE_FORMAT_ATTRS = {
|
|
|
|
short: %i[identifier name offset],
|
2021-12-06 19:14:07 -05:00
|
|
|
abbr: %i[identifier abbr],
|
2020-12-05 10:09:32 -05:00
|
|
|
full: %i[identifier name abbr offset formatted_offset]
|
|
|
|
}.freeze
|
|
|
|
private_constant :TIME_ZONE_FORMAT_ATTRS
|
|
|
|
|
|
|
|
# format:
|
|
|
|
# * :full - all available fields
|
|
|
|
# * :short (default)
|
|
|
|
#
|
|
|
|
# Example:
|
|
|
|
# timezone_data # :short by default
|
|
|
|
# timezone_data(format: :full)
|
|
|
|
#
|
|
|
|
def timezone_data(format: :short)
|
|
|
|
attrs = TIME_ZONE_FORMAT_ATTRS.fetch(format) do
|
|
|
|
valid_formats = TIME_ZONE_FORMAT_ATTRS.keys.map { |k| ":#{k}"}.join(", ")
|
2021-05-04 11:10:36 -04:00
|
|
|
raise ArgumentError, "Invalid format :#{format}. Valid formats are #{valid_formats}."
|
2020-12-05 10:09:32 -05:00
|
|
|
end
|
|
|
|
|
2020-12-02 10:09:37 -05:00
|
|
|
ActiveSupport::TimeZone.all.map do |timezone|
|
|
|
|
{
|
|
|
|
identifier: timezone.tzinfo.identifier,
|
|
|
|
name: timezone.name,
|
|
|
|
abbr: timezone.tzinfo.strftime('%Z'),
|
|
|
|
offset: timezone.now.utc_offset,
|
|
|
|
formatted_offset: timezone.now.formatted_offset
|
2020-12-05 10:09:32 -05:00
|
|
|
}.slice(*attrs)
|
2020-12-02 10:09:37 -05:00
|
|
|
end
|
|
|
|
end
|
2021-07-28 14:10:23 -04:00
|
|
|
|
2021-12-07 10:15:03 -05:00
|
|
|
def local_timezone_instance(timezone)
|
2021-11-08 22:42:22 -05:00
|
|
|
return Time.zone if timezone.blank?
|
|
|
|
|
|
|
|
ActiveSupport::TimeZone.new(timezone) || Time.zone
|
|
|
|
end
|
|
|
|
|
2021-07-28 14:10:23 -04:00
|
|
|
def local_time(timezone)
|
2021-10-01 11:12:53 -04:00
|
|
|
return if timezone.blank?
|
|
|
|
|
2021-12-07 10:15:03 -05:00
|
|
|
time_zone_instance = local_timezone_instance(timezone)
|
2021-07-28 14:10:23 -04:00
|
|
|
time_zone_instance.now.strftime("%-l:%M %p")
|
|
|
|
end
|
2020-12-02 10:09:37 -05:00
|
|
|
end
|