date.ex 1.2 KB

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