Convert ecto date to another format

I have a date inside Ecto schema yy/mm/dd

        date =    ~D[2021-07-22]

I want to convert it into this format mm/dd/yy to use it in my template.

       date = ~D[07-22-2021]

I have been using Timex, but didn’t figure out which method to use to convert it into this format.

Thanks,

If you want the formatted string for your template in the format “month-day-year” there are a few options. You don’t need Timex but if it is already in use in your project there is no reason not to use it I guess. Here are some ways to format a Date struct:

defmodule DateFormatTest do
  use ExUnit.Case

  @date ~D[2021-07-22]
  @formatted_date "07-22-2021"

  test "format date with Calendar.strftime" do
    assert Calendar.strftime(@date, "%m-%d-%Y") == @formatted_date
  end

  test "format date with Timex.format" do
    assert Timex.format!(@date, "{0M}-{0D}-{YYYY}") == @formatted_date
  end

  test "format date with Timex.format and :strftime" do
    assert Timex.format!(@date, "%m-%d-%Y", :strftime) == @formatted_date
  end
end
1 Like