Ecto DateTime arithmetic

Working with timestamps in Elixir is still very much a point of contention within the community. There is a pretty robust library emerging called Timex, but it is not now part of the core of Elixir or Phoenix. I think using native Erlang is probably the simplest guaranteed-to-work solution for performing arithmetic on timestamps.

In the following example, I want an Ecto.DateTime which is 500 seconds later than the current time. Probably the most convenient way of doing this is to grab the current utc time, convert it to a native erlang epoch, and then cast it back.

(:calendar.datetime_to_gregorian_seconds(Ecto.DateTime.to_erl(Ecto.DateTime.utc)) + 500) |>
:calendar.gregorian_seconds_to_datetime |>
Posted in Ecto, Elixir

Leave a Reply

Your email address will not be published. Required fields are marked *