1

我正在使用 rails 应用程序作为 iOS 后端。有一个小问题 - 如何在 json 中使用用户的时区呈现时间戳?我正在使用默认的 UTC 时区。例如如何将其转换为 +2?也许有办法在渲染之前覆盖 as_json 方法来转换时间戳?

感谢帮助!

4

1 回答 1

4

您可以在渲染 json 之前将时间转换为用户的时区,然后将包含时区。

1.9.3p125 :006 > t = Time.now.utc
 => 2012-10-20 13:49:12 UTC 
1.9.3p125 :007 > {time: t}.to_json
 => "{\"time\":\"2012-10-20T13:49:12Z\"}" 
1.9.3p125 :008 > t = Time.now.in_time_zone("Beijing")
 => Sat, 20 Oct 2012 21:49:19 CST +08:00 
1.9.3p125 :009 > {time: t}.to_json
 => "{\"time\":\"2012-10-20T21:49:19+08:00\"}" 

更新:要将时间转换为用户的时区以进行序列化,您可以覆盖此方法read_attribute_for_serialization。参见 ActiveModel 的 lib/active_model/serialization.rb:

# Hook method defining how an attribute value should be retrieved for
# serialization. By default this is assumed to be an instance named after
# the attribute. Override this method in subclasses should you need to
# retrieve the value for a given attribute differently:
#
#   class MyClass
#     include ActiveModel::Validations
#
#     def initialize(data = {})
#       @data = data
#     end
#
#     def read_attribute_for_serialization(key)
#       @data[key]
#     end
#   end
#
alias :read_attribute_for_serialization :send
于 2012-10-20T13:51:08.737 回答