Luke's profileLuke FanPhotosBlogLists Tools Help

Blog


    October 09

    Rails里面的时区

    由于把服务器放在国外了,所以就必须处理Rails里面的时区问题,否则的话,进行当日统计就总是不对。

    最笨的办法是直接计算出服务器所在的时区,和北京时间之间的差距,进行手动处理。

    后来发现了一个简单的办法,就是直接使用ActiveSupport中的时区函数。

    首先要做的是确定服务器端的时区。

    在本地运行 rake time:zones:local ,列出本地的时区。

    结果为:

    * UTC +08:00 *
    Beijing
    Chongqing
    Hong Kong
    Irkutsk
    Kuala Lumpur
    Perth
    Singapore
    Taipei
    Ulaan Bataar
    Urumqi

     

    我们选择北京。

    在environment.rb中将修改

    config.time_zone = 'UTC' 改为 config.time_zone = 'Beijing'

    这个时候,我们存入数据库中的时间就都是Beijing时间了,所有ActiveRecord中保存的created_at和updated_at,就都是北京时间了。

    但是这个时候如果执行Time.now或者Time.new,得到的还是当地时间。而且在比较的时候,非常麻烦。

    所以,我们需要编写以下代码来直接取出北京时间。

    Time.zone = “Beijing”

    n = Time.zone.now

    下面来做一个实验验证一下。

    首先修改environment.rb将config.time_zone = 'UTC'修改为config.time_zone = 'Pacific Time (US & Canada)'

    然后进入console状态, ruby script/console

    输入Time.now

    得到的还是:Fri Oct 09 11:08:50 +0800 2009,这是北京时间,而不是太平洋时间。

    然后在Person里面添加一条记录。

    p = Person.create :name = ‘Luke Fan’

    =>#<Person id: 3, name: "Luke Fan", created_at: "2009-10-09 03:13:40", updated_at: "2009-10-09 03:13:40">

    然后,键入:p.created_at

    => Thu, 08 Oct 2009 20:13:40 PDT -07:00

    好了,数据库里面存的已经是太平洋时间了。

    然后执行:

    Time.zone = 'Pacific Time (US & Canada)'

    n = Time.zone.now

    结果出来了:

    => Thu, 08 Oct 2009 20:30:12 PDT -07:00

    现在,可以在任意时区的服务器上,放置任意时区的应用了。

    Comments

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Trackbacks

    The trackback URL for this entry is:
    http://fl1972.spaces.live.com/blog/cns!85DD60846AD95DC7!690.trak
    Weblogs that reference this entry
    • None