开发者

Timezones in Rails

I have an application where I want to allow the user to set timezones. When the user creates a reminder entry, the entry will be stored in db in UTC. But when he opens the calendar entry in the app, he should see the entry in his selected timezone. I am using Chronic but that is immaterial here.

In my ApplicationController.rb, I have the following string :

before_filter :set_user_time_zone
...
def set_user_time_zone
    Time.zone = current_user.timezone if user_signed_in?
end
开发者_JAVA百科

After this, the entries are still saved in UTC but with the time difference. For example, I set the timezone as - "Delhi" which is +530 from UTC. When I want to save calendar entry for "Jan, 16 - 12:15 AM" - the database is populated with "2011-01-15 18:45:19 UTC" - so its 5:30 hours before the actual time I want to save.

In the UI also I keep seeing this entry instead of the the time displayed in the current user's timezone.

I want to know what should be correct way to handle this kind of timezone features in rails.


In the database you need to store the time in UTC and than for UI you need to convert it in the User's timezone.

Example in rails console:

Time.zone = "New Delhi"         #=> "New Delhi"

Time.now                        # => 2011-01-15 16:45:18 -0600

Time.now.in_time_zone           # => Sun, 16 Jan 2011 04:15:26 IST +05:30
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜