如果我們的系統需要支持全球用戶,怎樣保證不同時區的用戶顯示正確的本地時間呢
我們可以讓用戶選擇自己的時區,記錄在數據庫,然后轉換時間后顯示
如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
安徽新華電腦學校專業職業規劃師為你提供更多幫助【在線咨詢】