作者:Ryan Daigle 来源:JavaEye   酷勤网收集 2008-05-30

摘要
  支持Rails软件的time-zone插件不只一个,现在Rails自己已经提供方式来解决timezones问题,虽然依然基于tzinfo gem。设置Time.zone的变量为本地timezone,以后所有时间都会自动处理映射为本地时间,并存储为UTC进入数据库。

系列文章汇总《Ruby on Rails 2.1新特性

支持Rails软件的time-zone插件不只一个,现在Rails自己已经提供方式来解决timezones问题,虽然依然基于tzinfo gem。

下面是具体方法。设置Time.zone的变量为本地timezone,以后所有时间都会自动处理映射为本地时间,并存储为UTC进入数据库。

Ruby代码 复制代码
  1. # Set the local time zone   
  2. Time.zone = "Pacific Time (US & Canada)"  
  3.   
  4. # All times will now reflect the local time   
  5. article = Article.find(:first)   
  6. article.published_at #=> Wed, 30 Jan 2008 2:21:09 PST -08:00   
  7.   
  8. # Setting new times in UTC will also be reflected in local time   
  9. article.published_at = Time.utc(2008, 1, 1, 0)   
  10. article.published_at  #=> Mon, 31 Dec 2007 16:00:00 PST -08:00  


在rails应用中真正使用,可以增加:

Ruby代码 复制代码
  1. class ApplicationController < ActionController::Base   
  2.   
  3.   before_filter :set_timezone  
  4.   
  5.   def set_timezone   
  6.     # current_user.time_zone #=> 'London'   
  7.     Time.zone = current_user.time_zone   
  8.   end  
  9. end  


这样你的controller actions 和 views 能够应用用户自己的timezone。

当然可以设置缺省的timezone:

Ruby代码 复制代码
  1. Rails::Initializer.run do |config|   
  2.   config.time_zone = "Hawaii"  
  3. end  


获得当前时间是:

Ruby代码 复制代码
  1. # Instead of Time.now   
  2. Time.zone.now  
原文:ryandaigle.com
来自:http://www.javaeye.com/news/2417

分类: .NET技术 网页设计 交互设计

上一篇:Rails2.1新特性之六:UTC-based Migration   下一篇:eBay 的数据量