Rails 将 json 渲染到 AngularJS 前端。时间变成00:00:00

Rails render json to AngularJS frontend. Time becomes 00:00:00

我正在使用 Rails' 渲染方法将渲染的 json 传递给 AngularJS 前端。日期已成功通过。当我在后端尝试 puts 时,渲染的 json 对象也有正确的时间。但由于某种原因,所有时间都在前端变为 00:00:00 。

Rails 后端中的代码:

... // a lot of other stuff

respond_to do |format|
  format.json do
    render json: @entries
  end
end

AngularJS 前端中的代码:

XXX.query(params).then((response) => {
  console.log(response);
  ...
  // a lot of other stuff
}

后台打印的部分响应:

[{"id":101752,"version":1,"date":"2018-06-01T00:00:00.000Z","date_created":"2018-06-02T01:56:44.000Z","last_updated":"2018-06-02T01:56:44.000Z"},{"date":"2018-06-04T00:00:00.000Z","date_created":"2018-06-05T03:36:14.000Z","last_updated":"2018-06-05T03:36:14.000Z"}]

你可以看到时间戳都有时间(除了 "date" 应该有 00:00:00 的时间)。但是,当它到达前端时,所有时间戳都变成 00:00:00.

前端打印的部分响应:

JSON response frontend print out.png

现在我知道解决这个问题的唯一方法是使用 strftime() 在序列化程序中为每个时间戳添加一个函数。它会将时间戳转换为字符串,然后再将其转换为 JSON。但这将是非常低效的,因为我需要为每个时间戳向每个序列化程序添加 strftime() 函数。有没有人有更好的解决方案?另外,有谁知道 rails 渲染方法和时间戳到底发生了什么?

找到解决方案。 AngularJS 前端无法识别由 Rails 呈现的 JSON 中的默认日期格式。 在 config/initializer/ams.rb 文件中,您可以通过添加 ActiveSupport::JSON::Encoding.use_standard_json_time_format = false 行来关闭标准 JSON 时间格式。 这将影响现有的前端日期时间格式,但它成功地使 AngularJS 能够识别由 Rails 在 JSON 中呈现的 TimeWithZone。