Module: TimeZoneHelper

Included in:
API::Entities::User, Gitlab::ContributionsCalendar
Defined in:
app/helpers/time_zone_helper.rb

Instance Method Summary collapse

Instance Method Details

#local_time(timezone) ⇒ Object



55
56
57
58
59
60
# File 'app/helpers/time_zone_helper.rb', line 55

def local_time(timezone)
  return if timezone.blank?

  time_zone_instance = local_timezone_instance(timezone)
  time_zone_instance.now.strftime("%-l:%M %p")
end

#local_timezone_instance(timezone) ⇒ Object



49
50
51
52
53
# File 'app/helpers/time_zone_helper.rb', line 49

def local_timezone_instance(timezone)
  return Time.zone if timezone.blank?

  ActiveSupport::TimeZone.new(timezone) || Time.zone
end

#timezone_data(format: :short) ⇒ Object

format:

* :full - all available fields
* :short (default)

Example:

timezone_data # :short by default
timezone_data(format: :full)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/helpers/time_zone_helper.rb', line 19

def timezone_data(format: :short)
  attrs = TIME_ZONE_FORMAT_ATTRS.fetch(format) do
    valid_formats = TIME_ZONE_FORMAT_ATTRS.keys.map { |k| ":#{k}" }.join(", ")
    raise ArgumentError, "Invalid format :#{format}. Valid formats are #{valid_formats}."
  end

  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
    }.slice(*attrs)
  end
end

#timezone_data_with_unique_identifiers(format: :short) ⇒ Object

The identifiers in ‘timezone_data` are not unique. Some cities (e.g. London and Edinburgh) have the same `identifier` value (e.g. “Europe/London”). This method merges such entries into one, joining the city names. This unique list is better suited for selectboxes etc.



40
41
42
43
44
45
46
47
# File 'app/helpers/time_zone_helper.rb', line 40

def timezone_data_with_unique_identifiers(format: :short)
  timezone_data(format: format)
    .group_by { |entry| entry[:identifier] }
    .map do |_identifier, entries|
      names = entries.map { |entry| entry[:name] }.sort.join(', ') # rubocop:disable Rails/Pluck -- Not a ActiveRecord object
      entries.first.merge({ name: names })
    end
end