作者: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进入数据库。
- # Set the local time zone
- Time.zone = "Pacific Time (US & Canada)"
- # All times will now reflect the local time
- article = Article.find(:first)
- article.published_at #=> Wed, 30 Jan 2008 2:21:09 PST -08:00
- # Setting new times in UTC will also be reflected in local time
- article.published_at = Time.utc(2008, 1, 1, 0)
- article.published_at #=> Mon, 31 Dec 2007 16:00:00 PST -08:00
# Set the local time zone Time.zone = "Pacific Time (US & Canada)" # All times will now reflect the local time article = Article.find(:first) article.published_at #=> Wed, 30 Jan 2008 2:21:09 PST -08:00 # Setting new times in UTC will also be reflected in local time article.published_at = Time.utc(2008, 1, 1, 0) article.published_at #=> Mon, 31 Dec 2007 16:00:00 PST -08:00
在rails应用中真正使用,可以增加:
- class ApplicationController < ActionController::Base
- before_filter :set_timezone
- def set_timezone
- # current_user.time_zone #=> 'London'
- Time.zone = current_user.time_zone
- end
- end
class ApplicationController < ActionController::Base
before_filter :set_timezone
def set_timezone
# current_user.time_zone #=> 'London'
Time.zone = current_user.time_zone
end
end
这样你的controller actions 和 views 能够应用用户自己的timezone。
当然可以设置缺省的timezone:
- Rails::Initializer.run do |config|
- config.time_zone = "Hawaii"
- end
Rails::Initializer.run do |config| config.time_zone = "Hawaii" end
获得当前时间是:
- # Instead of Time.now
- Time.zone.now
# Instead of Time.now Time.zone.now原文:ryandaigle.com
来自:http://www.javaeye.com/news/2417


