每天一剂Rails良药之Dealing With Time-zones

UTC时间+时区偏移=本地时间
如果我们的系统需要支持全球用户,怎样保证不同时区的用户显示正确的本地时间呢
我们可以让用户选择自己的时区,记录在数据库,然后转换时间后显示
如users表有一个string的timezone字段记录时区
而恰好Rails里有一个TimeZone类,TimeZone.all可以得到所有时区:
class User < ActiveRecord::Base
  composed_of :tz,
              :class_name => 'TimeZone',
              :mapping => %w(time_zone name)

class ApplicationController < ActionController::Base
  def user2utc(time)
    current_user.tz.unadjust(time)
  end

  def utc2user(time)
    current_user.tz.adjust(time)
  end
end

你可能感兴趣的:(ActiveRecord,Rails)