How to convert a String into an Ecto.DateTime in E

2019-04-10 15:57发布

问题:

I need to convert a string containing a valid UTC time to an Ecto.DateTime one, which I will insert it into my database with the correct format later. I have tried using the Ecto.DateTime.cast(date) method but it doesn't seem to work. The string is Sat Aug 04 11:48:27 +0000 2012 and comes from the Twitter API.

I know there are libraries such as Timex which I didn't inspect yet. Is there any easy working solution already built in Elixir?

回答1:

There's no built-in solution in Elixir or Erlang for parsing DateTime values of this format:

Sat Aug 04 11:48:27 +0000 2012

You can certainly write a parser yourself, but it's neither going to be short or simple. You'll have to split the string, get the values of both date and time parameters, convert month strings to month integers, parse the timezone, represent the complete value in Elixir/Erlang DateTime formats and then finally cast it to Ecto.DateTime. See the following links:

  • Elixir Tips - Date Parsing
  • Erlang - How Can I Parse RFC1123 Dates Into An Erlang Term?
  • Convert timestamp to datetime in erlang

Using Timex is the best option here.

It's a well written library that allows you to stay away from the chaos of inner workings of Date/Time. With Timex, you can parse your string like this:

"Sat Aug 04 11:48:27 +0000 2012"
|> Timex.parse!("%a %b %d %T %z %Y", :strftime)
|> Ecto.DateTime.cast!

# => #Ecto.DateTime<2012-08-04 11:48:27>

Note: Timex has built-in support for a lot of the common DateTime formats, and I found it weird that a DateTime format being sent by Twitter wasn't supported - so I wrote one for you. Maybe double check to see if your string is correct? Also take a look at Timex Parsing and Formatting documentation.