Skip to content

Commit

Permalink
fix: Daylight saving
Browse files Browse the repository at this point in the history
  • Loading branch information
Matsa59 committed Nov 22, 2023
1 parent 230963f commit ce777fe
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/cocktail/util.ex
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,22 @@ defmodule Cocktail.Util do
def shift_time(datetime, opts) do
datetime
|> Timex.shift(opts)
|> shift_dst(datetime)
|> no_ms()
end

def no_ms(time) do
Map.put(time, :microsecond, {0, 0})
end

# In case of datetime we may expect the same timezone hour
# For example after daylight saving 10h MUST still 10h the next day.
# This behaviour could only happen on datetime with timezone (that include `std_offset`)
defp shift_dst(time, datetime) do
if offset = Map.get(datetime, :std_offset) do
Timex.shift(time, seconds: offset - time.std_offset)
else
time
end
end
end
30 changes: 30 additions & 0 deletions test/cocktail/daily_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,34 @@ defmodule Cocktail.DailyTest do
|> Cocktail.Schedule.occurrences(~N[2015-01-24 18:30:00])
|> Enum.take(100) == [~N[2015-01-24 18:30:00]]
end

test "generating occurrences with spring forward transition" do
schedule =
~Y[2022-03-12 18:00:00 America/Los_Angeles]
|> Schedule.new()
|> Schedule.add_recurrence_rule(:daily)

times = schedule |> Schedule.occurrences() |> Enum.take(3)

assert times == [
~Y[2022-03-12 18:00:00 America/Los_Angeles],
~Y[2022-03-13 18:00:00 America/Los_Angeles],
~Y[2022-03-14 18:00:00 America/Los_Angeles]
]
end

test "generating occurrences with fall back transition" do
schedule =
~Y[2022-11-05 18:00:00 America/Los_Angeles]
|> Schedule.new()
|> Schedule.add_recurrence_rule(:daily)

times = schedule |> Schedule.occurrences() |> Enum.take(3)

assert times == [
~Y[2022-11-05 18:00:00 America/Los_Angeles],
~Y[2022-11-06 18:00:00 America/Los_Angeles],
~Y[2022-11-07 18:00:00 America/Los_Angeles]
]
end
end
15 changes: 15 additions & 0 deletions test/cocktail/weekly_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,19 @@ defmodule Cocktail.WeeklyTest do
~Y[2017-01-09 10:00:00 America/Los_Angeles]
]
end

test "Weekly with dst transition" do
times =
~Y[2022-03-12 06:00:00 America/Los_Angeles]
|> Cocktail.schedule()
|> Schedule.add_recurrence_rule(:weekly)
|> Cocktail.Schedule.occurrences()
|> Enum.take(3)

assert times == [
~Y[2022-03-12 06:00:00 America/Los_Angeles],
~Y[2022-03-19 06:00:00 America/Los_Angeles],
~Y[2022-03-26 06:00:00 America/Los_Angeles]
]
end
end

0 comments on commit ce777fe

Please sign in to comment.