4

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)?

Alex Kovshovik
  • 4,085
  • 4
  • 35
  • 36

1 Answers1

3

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.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • Great, thank you - this worked. I changed the field type form Ecto.DateTime to Timex.Ecto.DateTime, then I had to make sure my datetime value is formatred properly with a timezone: "2016-12-01 12:00:00-0500" or "2016-12-01 12:00:00Z". Commit that fixes it in my project: https://github.com/alex-kovshovik/shovik_com/commit/5c41fa26b8d8e1a36fe1c9d00a4a05fe29081a7c – Alex Kovshovik Dec 01 '16 at 15:20