如何将String转换为Elixir中的Ecto.DateTime? [英] How to convert a String into an Ecto.DateTime in Elixir?

查看:558
本文介绍了如何将String转换为Elixir中的Ecto.DateTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个包含有效的UTC时间的字符串转换为一个 Ecto.DateTime 一个,我将把它插入到我的数据库中,然后使用正确的格式。我尝试使用 Ecto.DateTime.cast(date)方法,但似乎不起作用。字符串是 Sat Aug 04 11:48:27 +0000 2012 并来自Twitter API。

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.

我知道有没有我没有检查的 Timex 的库。在Elixir中有没有任何简单的工作解决方案?

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

推荐答案

没有内置解决方案 Elixir或Erlang用于解析此格式的 DateTime 值:

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

你可以自己编写一个解析器,但它不会要短或简单。您必须拆分字符串,获取日期和时间参数的值,将月份字符串转换为月份整数,解析时区,表示Elixir / Erlang DateTime格式中的完整值,然后最终将其转换为 Ecto.DateTime 。请参阅以下链接:

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

使用 Timex 是这里最好的选择。

Using Timex is the best option here.

这是一个写得很好的图书馆,可以让你远离日期的内部工作的混乱/时间。使用 Timex ,您可以解析这样的字符串:

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>






注意:Timex有内置的支持很多常见的DateTime格式,我发现Twitter发送的DateTime格式不受支持,所以我为你写了一个。也许双重检查你的字符串是否正确?另请参阅Timex 解析格式化文档。

这篇关于如何将String转换为Elixir中的Ecto.DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆