2012-10-20 112 views
1

我正在使用Rails應用程序作爲iOS後端。有一個小問題 - 如何使用json中的用戶時區顯示時間戳?我使用的是默認的UTC時區。如何將它轉換爲+2?也許有辦法如何重寫as_json方法來轉換渲染之前的時間戳?Rails渲染json與正確的時區

感謝您的幫助!

回答

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\"}" 

UPDATE:將時間轉換成用戶的時區爲系列化,您可以覆蓋此方法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 
+0

例如,我需要使用'created_at'字段呈現模型用戶。我需要渲染洞模型一次,所以我需要覆蓋用戶模型中的to_json方法。但我沒有任何想法如何去做。 –

+0

查看我的答案更新。 – Yanhao

+0

是的。看起來像是有效的。有點彎曲的解決方案=)謝謝! –