How to convert a String into an Ecto.DateTime in Elixir?

為{幸葍}努か 提交于 2019-12-06 06:15:49

问题


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.



来源:https://stackoverflow.com/questions/40444970/how-to-convert-a-string-into-an-ecto-datetime-in-elixir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!