我需要将包含有效 UTC 时间的字符串转换为Ecto.DateTime
一个,稍后我会将其以正确的格式插入到我的数据库中。我尝试过使用Ecto.DateTime.cast(date)
方法但似乎不起作用。该字符串是Sat Aug 04 11:48:27 +0000 2012
来自 Twitter API。
我知道有一些图书馆,例如Timex我还没有检查过。 Elixir 中是否已经内置了任何简单的工作解决方案?
没有内置的解决方案在 Elixir 或 Erlang 中进行解析DateTime
这种格式的值:
Sat Aug 04 11:48:27 +0000 2012
您当然可以自己编写一个解析器,但它既不会短也不简单。您必须拆分字符串,获取日期和时间参数的值,将月份字符串转换为月份整数,解析时区,以 Elixir/Erlang DateTime 格式表示完整值,然后最终将其转换为Ecto.DateTime
。请参阅以下链接:
- Elixir 技巧 - 日期解析 https://makandracards.com/neoukelixirtips/22065-dates-date-formatting-and-parsing
- Erlang - 如何将 RFC1123 日期解析为 Erlang 术语? https://stackoverflow.com/questions/21827905/erlang-how-can-i-parse-rfc1123-dates-into-an-erlang-term
- 在erlang中将时间戳转换为日期时间 https://stackoverflow.com/questions/825151/convert-timestamp-to-datetime-in-erlang
Using Timex https://github.com/bitwalker/timex是这里最好的选择。
这是一个编写良好的库,可以让您远离日期/时间内部工作的混乱。和Timex
,你可以像这样解析你的字符串:
"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 https://hexdocs.pm/timex/parsing.html and Formatting https://hexdocs.pm/timex/formatting.html documentation.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)