简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM