summaryrefslogtreecommitdiff
path: root/app/helpers/time_zone_helper.rb
blob: 29bd5a846519e2550abfeb21951caa370d828a26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# frozen_string_literal: true

module TimeZoneHelper
  TIME_ZONE_FORMAT_ATTRS = {
    short: %i[identifier name offset],
    abbr: %i[identifier abbr],
    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(", ")
      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

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

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

  def local_time(timezone)
    return if timezone.blank?

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