日付の表示
Rails
Railsから取得した日付を含むJSON形式のデータを、Extで表示するときのメモです。Railsでのタイムゾーンを含む日付はTimeWithZoneクラスで、これをto_jsonでJSON形式に変換すると、以下の様になります。
ここでいうタイムゾーンは、config/environment.rbの"config.time_zone"の設定です。
今回調べてはじめて知ったのですがこの日付形式はISO-8601というそうです。config/initializers/new_rails_defaults.rbで記述されています。2.1でプロジェクトを作成した場合に、このファイルが作成されてISO-8601形式を使うよう自動で設定され、、Rails 3からはISO-8601形式がデフォルトになるようです。
# These settings change the behavior of Rails 2 apps and will be defaults # for Rails 3. You can remove this initializer when Rails 3 is released. # Include Active Record class name as root for JSON serialized output. ActiveRecord::Base.include_root_in_json = true # Store the full class name (including module namespace) in STI type column. ActiveRecord::Base.store_full_sti_class = true # Use ISO 8601 format for JSON serialized times and dates. ActiveSupport.use_standard_json_time_format = true # <--ここ! # Don't escape HTML entities in JSON, leave that for the #json_escape helper. # if you're including raw json in an HTML page. ActiveSupport.escape_html_entities_in_json = false
"ActiveSupport.use_standard_json_time_format"の値をfalseに変更することで、ISO-8601を使わないようにできます。
この前書いたActiveRecordのデータをJSONにしたときにクラス名のハッシュにするかどうかもここで設定ができました(ActiveRecord::Base.store_full_sti_class=falseにする)。
Ext
Ext側ではISO-8601形式の日付はそのままではparseに失敗するので、形式を指定してあげる必要があります。Ext.data.JsonStoreを使う場合だと、コンフィグオプションのfieldsで日付形式(dateFormat)を指定します。
store = new Ext.data.JsonStore({ // 省略 fields : [{ name:'updated_datetime', type: 'date', dateFormat: 'c' } // 省略 });
ISO-8601形式の場合には、'c'を指定します。ここで指定できる値は、Dateに一覧があります。
あとはこれまでの形式と同様に表示の際にExt.util.Format.dateRendererを使ってフォーマットしてあげればよいです。