【发布时间】:2017-10-05 02:54:16
【问题描述】:
在我的 Phoenix 应用程序中,我正在尝试将事件记录插入到具有 start_time 和 end_time 字段的数据库中 - 日期时间数据已经在客户端上转换为 ISO 字符串格式并传递给Phoenix API 作为 JSON 数据,但是当我尝试插入时这给我带来了一些麻烦 - 模型期望这些值是 :utc_datetime 所以我需要转换它们 - 我通读了文档,但我仍然不确定...
首先,这是模型的架构:
@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 数据如下所示:
{
"start_time": "2017-09-28T18:31:32.223Z",
"end_time": "2017-09-28T19:31:32.223Z",
"description": "Test insert"
}
如果我(错误地)尝试按原样插入这些数据,语句将如下所示:
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?
【问题讨论】:
标签: datetime elixir phoenix-framework ecto