elixirphoenix-frameworkectotimex

How do you parse a date and time string into a type compatible with Elixir's Ecto.DateTime?


In my Phoenix app I have a form with a date/time field that puts datetime value into params in the following format:

2016-11-30 20:00

I can parse it using Timex library:

Timex.parse("2016-11-30 20:00", "%Y-%m-%d %H:%M", :strftime)

Which results in:

{:ok, ~N[2016-11-30 20:00:00]}

"~N[2016-11-30 20:00:00]" is a "naive" datetime value, which does not include a time zone. Problem is: this value type does not match to Ecto.DateTime, so I can't put it into a changeset and save into my database.

Question: How do you parse a date and time in a string into a Ecto.DateTime value with the specific timezone (US/Eastern, for example)?


Solution

  • While there are many ways to produce an ecto-compatible value out of naïve one, there is more robust solution: Timex Plugin for Ecto.

    It’s source code might inspire everybody who still wants to re-implement the wheel in-house.