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
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.
The default time zone in Rails is UTC. As tempting as it may seem, it is best to leave the application-wide time zone as UTC and instead allow each individual user to set their own time zone.
Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With