Rails使用正确的时区渲染json

时间:2012-10-20 12:59:29

标签: ruby-on-rails json timezone

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

感谢您的帮助!

1 个答案:

答案 0 :(得分: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