Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.now in Elixir and Ecto

I want to get the current date-time stamp in Phoenix/Elixir without a third-party library. Or simply, I want something like DateTime.now(). How can I do that?

like image 855
darko Avatar asked Sep 05 '16 13:09

darko


2 Answers

Ecto has Ecto.DateTime.utc/1 to get the current time in UTC:

iex(1)> Ecto.DateTime.utc
#Ecto.DateTime<2016-09-05 13:30:04>
iex(2)> Ecto.DateTime.utc(:usec) # include microseconds
#Ecto.DateTime<2016-09-05 13:30:18.367318>

If you want the current time in the local system's timezone, you can do:

Ecto.DateTime.from_erl(:erlang.localtime)
like image 100
Dogbert Avatar answered Nov 13 '22 00:11

Dogbert


As of Ecto 3, Ecto.Date, Ecto.Time and Ecto.DateTime no longer exist, as stated here.

However, Elixir now ships with DateTime, Date and NaiveDateTime, which should be used.

iex(1)> DateTime.utc_now
#DateTime<2019-01-14 12:05:52.271492Z>
like image 31
Gabriel Prá Avatar answered Nov 13 '22 00:11

Gabriel Prá