Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse DateTime in Elixir?

How can I create (Ecto.)DateTime out of a tuple {DD, MM, YY}, or parse it from a string in Elixir? Should I use DateTime from Erlang for that?

I've googled but haven't found anything and there's nothing in the documentation about the matter, only about DateTime in general -- how to get the current date and time, for example.

Note that I don't want to use a third-party library such as Timex.

like image 932
Kooooro Avatar asked Dec 04 '16 18:12

Kooooro


Video Answer


1 Answers

Just adding to the answer given by Justin. Elixir's standard library can parse ISO 8601 dates.

iex> Date.from_iso8601("2015-01-23")
{:ok, ~D[2015-01-23]}

or with the bang-version, that might raise errors:

iex> Date.from_iso8601!("2015-01-23")
~D[2015-01-23]

If you want a full datetime from an ISO 8601 string, you'll have to be satisfied with a NaiveDateTime, since there's no reliable time zone information to go on.

iex> NaiveDateTime.from_iso8601("2015-01-23 23:50:07")
{:ok, ~N[2015-01-23 23:50:07]}

Beware, it will simply throw away time zone offsets.

There is going to be a from_iso8601/1 on DateTime in the future, but it was recently added and has not been released as of Elixir v1.3.4. It will preserve time zone offset, but set the time zone to UTC.

like image 195
Martin Svalin Avatar answered Oct 04 '22 09:10

Martin Svalin