Phoenix/Ecto-将ISO字符串转换为utc_datetime基本类型 [英] Phoenix/Ecto - converting ISO string into utc_datetime primitive type
问题描述
在Phoenix应用中,我试图将事件记录插入到具有start_time
和end_time
字段的数据库中-日期时间数据已经在客户端上转换为ISO字符串格式,并传递给了Phoenix API作为JSON数据,但这在尝试插入时给我造成了一些麻烦-该模型期望这些值是:utc_datetime
,因此我需要对其进行转换-我通读了文档,但我仍然不确定...
In my Phoenix app, I'm trying to insert an event record into the database that has fields for start_time
and end_time
- the datetime data will already be converted to ISO string format on the client and passed to the Phoenix API as JSON data, but this is causing me some trouble when I try to make an insert - the model is expecting those values to be :utc_datetime
so I need to convert them - I read through the documentation, but I'm still not sure...
首先,这是模型的架构:
First off, here's the schema for the model:
@primary_key {:id, :string, []}
@derive {Phoenix.Param, key: :id}
schema "calendar_event" do
field :start_time, :utc_datetime
field :end_time, :utc_datetime
field :description, :string
timestamps()
end
来自客户端的JSON数据如下:
JSON data from the client would look like:
{
"start_time": "2017-09-28T18:31:32.223Z",
"end_time": "2017-09-28T19:31:32.223Z",
"description": "Test insert"
}
如果我(不正确)尝试按原样插入此数据,则该语句将如下所示:
And if I were to (incorrectly) try to insert this data as-is, the statement would look like:
MyApp.Repo.insert(%MyApp.CalendarEvent{id: "calendar_event:test1", start_time:
"2017-09-28T18:31:32.223Z", end_time: "2017-09-28T19:31:32.223Z",
description: "Test insert"})
如预期的那样,这引发了我的日期时间数据does not match type :utc_datetime
的错误.好的,这很酷,但是我的问题是,对于已经存在于ISO字符串中的数据,我该如何将其转换为Elixir/Ecto将其识别为有效的:utc_datetime
?
As expected, this throws an error that my datetime data does not match type :utc_datetime
. Ok, that's cool, but my question is, with the data already in ISO string, how can I convert it to that Elixir/Ecto recognizes it as valid :utc_datetime
?
推荐答案
您想要:utc_datetime
字段的DateTime
结构,如您在此处的文档中所见:
You want a DateTime
struct for your :utc_datetime
field, as you can see in the docs here: https://hexdocs.pm/ecto/Ecto.Schema.html#module-primitive-types
您可以从iso字符串中获得DateTime
,就像上面的字符串一样:
You can get a DateTime
from an iso string like the one you had above like this:
iex> {:ok, dt, 0} = DateTime.from_iso8601("2017-09-28T18:31:32.223Z")
iex> dt
#DateTime<2017-09-28 18:31:32.223Z>
(元组中的零是UTC偏移量)
(The zero in the tuple is the UTC offset)
注意:Ecto 2.1中引入了对Elixir日历类型的支持. DateTime.from_iso8601/1
在Elixir 1.4中引入.
Note: Support for Elixir Calendar types was introduced in Ecto 2.1. DateTime.from_iso8601/1
was introduced in Elixir 1.4.
这篇关于Phoenix/Ecto-将ISO字符串转换为utc_datetime基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!