Pattern match on Timex date

I’m generating custom time select fields in my form and that’s the only way that comes to my mind how to do this.
But I’m sure there is a pattern match for that
I want to show only current year
unless it is the first of january then I want to show also the previous year.
or when its the end of year I want to show the next year

now = Timex.now
  defp year_select(now) do
    year = [now.year]
    year = if now.month == 1 and now.day == 1, do: [now.year - 1, now.year], else: year
    year = if now.month == 12 and now.day > Timex.shift(now, days: +4).day, do: [now.year, now.year + 1], else: year
    year
  end

now looks like:
~U[2019-10-23 19:57:12.649300Z]

defp year_select(%{year: y, month: 1, day: 1}, do: [y - 1, y]
defp year_select(%{year: y, month: 12, day: d), when d in 28..31, do: [y, y + 1]
defp year_select(%{year: y}, do: [y]

I hope I got the “end of year” match correct… I’m not quite sure what Timex.shift does, but it looks like you were checking for an overflow on the days when adding 4 days… Thats why I used 28..31, the last 4 days of december…

Perhaps that line would have been more obvious as now.year < Timex.shift(now, days: 4).year.

You could even use %DateTime{…} to make sure you get an actual date time, and not just a map with a :year key…

3 Likes

Thanks, with the end of year it’s exactly what I meant. I was confused by the ~U sygil that timex returns. With a map it makes more sense to me

sigil_U is just a pretty printed %DateTime{}.

i/1 and h/1 in iex are your friends.

2 Likes

Thanks - It helped me a lot