converting day and time to date in future using Elixir

Viewed 77

I have this data

%{
  day: "sun"
  since: ~T[13:30:00],
  till: ~T[14:30:00]
}

I am trying to make a DateTime from this, using

Enum.reduce_while(1..7, DateTime.utc_now(), fn _day, acc ->
  current_day =
    acc
      |> Timex.weekday()
      |> Timex.day_shortname()
      |> String.downcase()

  if current_day != hour.day,
    do: {:cont, Timex.shift(acc, days: 1)},
    else: {:halt, acc}
end)
|> DateTime.to_date()
|> NaiveDateTime.new(hour.since)
|> elem(1)
|> DateTime.from_naive!("Etc/UTC")

This works fine. but I am asking for a suggestion is there can be simpler approach to this?

1 Answers

I am not sure why would one use Timex for such trivial math. What you actually need, would be to ① add a proper number of days to Date.utc_today() and ② glue it with hour.since:

shift =
  ~w|mon tue wed thu fri sat sun|
  |> Enum.zip(1..7)
  |> Map.new()

date = Date.utc_today()
to_add =
  Integer.mod(7 + shift[hour.day] - Date.day_of_week(date), 7)

date
|> Date.add(to_add)
|> DateTime.new!(hour.since)
#⇒ ~U[2022-01-16 13:30:00Z]
Related