gpt4 book ai didi

json - 在 Phoenix JSON API 中接受日期

转载 作者:行者123 更新时间:2023-12-05 00:31:51 26 4
gpt4 key购买 nike

在 Phoenix 我有这个模型

schema "events" do
field :start_time, Ecto.DateTime
field :end_time, Ecto.DateTime
belongs_to :calendar, Weozo.Calendar

timestamps
end

@required_fields ~w(calendar_id start_time end_time)
@optional_fields ~w()

def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end

我有一个由脚手架生成的 JSON API Controller (通过 :api 管道),其中 create 函数如下所示
  def create(conn, %{"event" => event_params}) do
changeset = Event.changeset(%Event{}, event_params)

case Repo.insert(changeset) do
{:ok, event} ->
conn
|> put_status(:created)
|> put_resp_header("location", event_path(conn, :show, event))
|> render("show.json", event: event)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(Weozo.ChangesetView, "error.json", changeset: changeset)
end
end

这只是默认的样板。现在,我想用 Javascript 客户端创建一个事件,使用 jQuery 我这样做:
$.post('/api/events', 
{"event": {"calendar_id": 1, "start_time": Date.now(), "end_time": Date.now()}}
).always(function(r){console.log(r.responseText)})

它返回这个
{"errors":{"start_time":["is invalid"],"end_time":["is invalid"]}}

因此,默认情况下,Javascript 将日期发布为整数(Epoch 格式)。我在 curl 中尝试了很多变化,如下所示:

只是一个普通的约会
curl -X POST http://localhost:4000/api/events \
-H "Content-Type: application/json" \
-d '{"event": {"calendar_id": 1, "start_time": "2015-10-29", "end_time": "2015-10-29"}}'

RFC 1123 格式的日期
curl -X POST http://localhost:4000/api/events \
-H "Content-Type: application/json"
-d '{"event":{"calendar_id":"1","start_time":"Thu, 29 Oct 2015 20:11:54 GMT","end_time":"Thu, 29 Oct 2015 20:11:54 GMT"}}'

ISO 8601 格式的日期
curl -X POST http://localhost:4000/api/events \
-H "Content-Type: application/json"
-d '{"event":{"calendar_id":"1","start_time":"2015-10-29T20:12:30+0000","end_time":"2015-10-29T20:12:30+0000"}}'

它们都收到相同的“无效”错误消息。

所以 Phoenix 不接受 Epoch、RFC 1123 或 ISO 8601。我应该如何格式化我的日期让 Phoenix 接受它?

最佳答案

变更集将使用 Ecto.DateTime.cast/1 转换日期时间字段从文档:

• a binary in the "YYYY-MM-DD HH:MM:DD" format (may be separated by T and/or followed by "Z", as in 2014-04-17T14:00:00Z)

• a binary in the "YYYY-MM-DD HH:MM:DD.USEC" format (may be separated by T and/or followed by "Z", as in 2014-04-17T14:00:00.030Z)



时间应采用 ISO8601 格式:
2015-10-29T20:12:30Z

您可以在 JavaScript 中生成这样的字符串:
new Date().toISOString()

关于json - 在 Phoenix JSON API 中接受日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com