Today I Learned

hashrocket A Hashrocket project

Getting a date

Elixir 1.3 has introduced calendars and calendar types. Lets check out how to get a Date type!

You can use the new function and pass in year, month and day separately.

iex >, 6, 28)
{:ok, ~D[2008-06-28]}

If you want a nonsensical date you'll get an :error atom back.

iex >, 6, 31)
{:error, :invalid_date}

Elixir knows how to handle ISO8601 date formatted strings. Don't forget to zero pad that month value!

iex > Date.from_iso8601("2008-6-28")
{:error, :invalid_format}
iex > Date.from_iso8601("2008-06-28")
{:ok, ~D[2008-06-28]}

To support Erlang the from_erl function will accept a tuple.

iex > Date.from_erl({2008, 6, 28})
{:ok, ~D[2008-06-28]}

It's interesting that the date is inspected as a sigil.

iex > {:ok, d} = Date.from_erl({2008, 6, 28})
{:ok, ~D[2008-06-28]}
iex > d

Hey you can create a date with the new sigil syntax!

iex > ~D[2008-06-28]
See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.