'Finding records where the current time is x pm in rails

I am using active support to find time zones where it is x pm.

time_zones = ActiveSupport::TimeZone.all.select{ |time| time.now.hour == x }

Then find records in that time zone.

Record.where(time_zone: time_zones)

The time_zone in these records is set using the Geocoder gem (Geocoder.search("ip_addr")). The problem is that Geocoder gives a time_zone value like "Asia/Thimphu" but there is no such value in the ActiveSupport list(refer_this). In my record search, it is possible that it will skip records with time zone not listed in the ActiveSupport list despite being x pm in there.

Would be grateful of any solutions.



Solution 1:[1]

You could use the constant MAPPING in TimeZone class to get the TZInfo identifier from Rails timezone name.

zones = ActiveSupport::TimeZone.all.select { |zone| zone.now.hour == x }
zone_identifiers = zones.map { |zone| ActiveSupport::TimeZone::MAPPING[zone.name] }

Record.where(time_zone: zone_identifiers)

Update from comments

Also you could still save the record and get the identifiers using the mapping though:

zones = ActiveSupport::TimeZone.all.select { |zone| zone.now.hour == x }
zone_identifiers = zones.map { |zone| IANA_TO_ACTIVERECORD_BULLSHIT_TIMEZONE_MAPPING.filter_map { |k, v| k if v == zone.name } }.flatten

Record.where(time_zone: zone_identifiers)

but definitely cleaner to keep the Rails timezone names in the database.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1