How do I set Time.zone to UTC and keep it that way?
I have a Rails 3 application on Ruby 1.9.2 in which users enter business hours and they are st开发者_如何学Goored in a MySQL database. When a user does this, however, the entered time "8:00 AM" gets stored as 3pm in the database. I want it to be stored as they entered it, regardless of time zone. I figured the best way to do this is to set everything to UTC and have it ignore my time zone (Arizona), but Rails seems to be ignoring my setting. Example:
Time.zone = 'UTC'
mon_open_date = Time.parse(params[:venue][:mon_open_at]) rescue nil
# => 2011-04-27 08:00:00 -0700
The result in MySQL:
+-------------+
| mon_open_at |
+-------------+
| 15:00:00 |
+-------------+
1 row in set (0.00 sec)
Any ideas?
Time.parse always parses the string into your computer's local timezone. You need to use Time.zone.parse
in order to parse it as the specified timezone, UTC.
MySQL always uses the server's time zone setting, by default (though you can change that, if you are the database admin).
If you store your date/time values in TIMESTAMP columns, they are stored in a time-zone agnostic manner (being converted to UTC for storage, and then back to the server's time zone again for usage).
If you store your date/times in a DATETIME column, the values are stored exactly as you enter them - if you change the server's time zone, and then SELECT old values out of a DATETIME column, you will see exactly the same values as when you entered them.
Check out the documentation on DATETIME/TIMESTAMP columns for the finer points.
精彩评论