Fix timezone list when time changes (#2268)

This commit fixes an exception when calling `Timex.Timezone.get/2` after
there has been a timezone change. Similar issues have already been reported
in Timex (bitwaker/timex#691, bitwalker/timex#555, bitwalker/timex#625).

This skips timezones from the list when they fail to fetch, and use
`Timex.Timezone.get/2` to get the current offset using `DateTime.utc_now/0`
instead of the `NaiveDateTime` default.
pull/2273/head
Vinicius Brasil 4 years ago committed by GitHub
parent 1adda42a75
commit db03cc0ac6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,24 +1,35 @@
defmodule Plausible.Timezones do
@spec options() :: [{:key, String.t()}, {:value, String.t()}, {:offset, integer()}]
def options do
@spec options(DateTime.t()) :: [{:key, String.t()}, {:value, String.t()}, {:offset, integer()}]
def options(now \\ DateTime.utc_now()) do
Tzdata.zone_list()
|> Enum.map(&build_option/1)
|> Enum.reduce([], fn timezone_code, acc -> build_option(timezone_code, acc, now) end)
|> Enum.sort_by(& &1[:offset], :desc)
end
defp build_option(timezone_code) do
timezone_info = Timex.Timezone.get(timezone_code)
offset_in_minutes = timezone_info |> Timex.Timezone.total_offset() |> div(-60)
defp build_option(timezone_code, acc, now) do
case Timex.Timezone.get(timezone_code, now) do
%Timex.TimezoneInfo{} = timezone_info ->
offset_in_minutes = timezone_info |> Timex.Timezone.total_offset() |> div(-60)
hhmm_formatted_offset =
timezone_info
|> Timex.TimezoneInfo.format_offset()
|> String.slice(0..-4)
hhmm_formatted_offset =
timezone_info
|> Timex.TimezoneInfo.format_offset()
|> String.slice(0..-4)
[
key: "(GMT#{hhmm_formatted_offset}) #{timezone_code}",
value: timezone_code,
offset: offset_in_minutes
]
option = [
key: "(GMT#{hhmm_formatted_offset}) #{timezone_code}",
value: timezone_code,
offset: offset_in_minutes
]
[option | acc]
error ->
Sentry.capture_message("Failed to fetch timezone",
extra: %{code: timezone_code, error: inspect(error)}
)
acc
end
end
end

@ -11,4 +11,9 @@ defmodule Plausible.TimezonesTest do
hawaii = Enum.find(options, &(&1[:value] == "US/Hawaii"))
assert [key: "(GMT-10:00) US/Hawaii", value: "US/Hawaii", offset: 600] = hawaii
end
test "options/0 does not fail during time changes" do
options = Plausible.Timezones.options(~N[2021-10-03 02:31:07])
refute Enum.empty?(options)
end
end

Loading…
Cancel
Save