Module: TpCommon::Timezones

Defined in:
lib/tp_common/timezones.rb,
lib/tp_common/timezones/zone.rb

Defined Under Namespace

Classes: Zone

Constant Summary collapse

LIST_ZONES =
TpCommon.load_timezones.freeze

Class Method Summary collapse

Class Method Details

.converted_time(time, zone) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/tp_common/timezones.rb', line 50

def self.converted_time(time, zone)
  if time
    zone_value = LIST_ZONES[zone]

    if zone_value
      time.in_time_zone(zone_value[:name])
    else
      time
    end
  end
end

.current_date_in_time_zone(time_zone_key) ⇒ Object



5
6
7
# File 'lib/tp_common/timezones.rb', line 5

def self.current_date_in_time_zone(time_zone_key)
  self.converted_time(Time.now, time_zone_key).strftime('%Y-%m-%d %H:%M:%S').to_date
end

.list_for_selectObject



36
37
38
# File 'lib/tp_common/timezones.rb', line 36

def self.list_for_select
  LIST_ZONES.map{ |k, v| [self.zone_title(k), k] }
end

.list_zone_offsetsObject

return hash offsets. Ex: => 0, …



41
42
43
# File 'lib/tp_common/timezones.rb', line 41

def self.list_zone_offsets
  Hash[LIST_ZONES.map{ |k, v| [k, Time.now.in_time_zone(v[:name]).utc_offset] }]
end

.local_to_utc(time, zone) ⇒ Object



45
46
47
48
# File 'lib/tp_common/timezones.rb', line 45

def self.local_to_utc(time, zone)
  zone_value = LIST_ZONES[zone]
  ActiveSupport::TimeZone.new(zone_value[:name]).local_to_utc(time)
end

.offset_in_words(zone_name) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/tp_common/timezones.rb', line 9

def self.offset_in_words(zone_name)
  offset = Time.now.in_time_zone(zone_name).utc_offset
  in_words = 'GMT'

  hours = offset.abs / (60 * 60)

  in_words << (offset > 0 ? '+' : '-')
  in_words << format('%01d', hours)
  in_words
end

.relative_time_in_time_zone(time, time_zone_key) ⇒ Object



67
68
69
70
# File 'lib/tp_common/timezones.rb', line 67

def self.relative_time_in_time_zone(time, time_zone_key)
  zone = zone_abbreviation(time_zone_key)
  DateTime.parse(time.strftime("%d %b %Y %H:%M:%S #{time.in_time_zone(zone).formatted_offset}"))
end

.zone_abbreviation(time_zone_key) ⇒ Object



62
63
64
65
# File 'lib/tp_common/timezones.rb', line 62

def self.zone_abbreviation(time_zone_key)
  zone_value = LIST_ZONES[time_zone_key]
  zone_value[:name]
end

.zone_title(zone) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/tp_common/timezones.rb', line 20

def self.zone_title(zone)
  zone_value = LIST_ZONES[zone]
  return nil unless zone_value

  dst_icon = zone_value[:dst] ? '☀️' : ''

  [zone_value[:title], self.offset_in_words(zone_value[:name]), dst_icon].reject{|part| part.empty? }.join(" ")
end

.zone_title_without_dst(zone) ⇒ Object



29
30
31
32
33
34
# File 'lib/tp_common/timezones.rb', line 29

def self.zone_title_without_dst(zone)
  zone_value = LIST_ZONES[zone]
  return nil unless zone_value

  [zone_value[:title], self.offset_in_words(zone_value[:name])].reject{|part| part.empty? }.join(" ")
end