在我的Phoenix應用程序中,我試圖將事件記錄插入到數據庫中,該數據庫的字段爲start_time
和end_time
- 日期時間數據已經轉換爲ISO字符串格式在客戶端,並作爲JSON數據傳遞給Phoenix API,但是當我嘗試插入數據時,這會導致一些麻煩 - 模型期望這些值爲:utc_datetime
,因此我需要將它們轉換 - 我通讀文檔,但我仍然不知道...Phoenix/Ecto - 將ISO字符串轉換爲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
?