我正在将Rails应用程序用作iOS后端。存在小问题 - 如何使用JSON中用户的时区渲染时间戳?我正在使用默认的UTC时区。例如,如何将其转换为 2?也许有办法如何覆盖AS_JSON方法在渲染之前转换时间戳?
感谢您的帮助!
您可以在渲染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