date.ex 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. defmodule CvGenView.Date do
  2. use Phoenix.Component
  3. use CvGen.RegenerateOnCompilation
  4. attr(:start_date, :string, required: true)
  5. attr(:end_date, :string, default: nil)
  6. def time_span(assigns) when assigns.start_date == assigns.end_date,
  7. do: ~H"""
  8. <div class="period">
  9. <.date date={@start_date} />
  10. </div>
  11. """
  12. def time_span(assigns),
  13. do: ~H"""
  14. <div class="period">
  15. <.date date={@start_date} /> - <.date date={@end_date} />
  16. </div>
  17. """
  18. attr(:date, :any)
  19. attr(:rest, :global)
  20. def date(assigns) do
  21. ~H"""
  22. <time datetime={@date} {@rest}><%= localized(@date) %></time>
  23. """
  24. end
  25. defp localized(nil), do: "Aujourd'hui"
  26. defp localized(date) when is_binary(date) do
  27. case String.split(date, "-") do
  28. [year, month] ->
  29. {year, month} = {String.to_integer(year), String.to_integer(month)}
  30. Date.new!(year, month, 1) |> localized()
  31. [year] ->
  32. year
  33. end
  34. end
  35. defp localized(date) when is_struct(date, Date),
  36. do:
  37. Calendar.strftime(
  38. date,
  39. "%B %Y",
  40. month_names: fn month ->
  41. {"Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre",
  42. "Octobre", "Novembre", "Décembre"}
  43. |> elem(month - 1)
  44. end
  45. )
  46. end