Reputation: 1027
Now I am developing a rails project. My database is MySQL.
I check my MySQL's timezone:
mysql> SELECT @@global.time_zone, @@session.time_zone;
+--------------------+---------------------+
| @@global.time_zone | @@session.time_zone |
+--------------------+---------------------+
| SYSTEM | SYSTEM |
+--------------------+---------------------+
And the SYSTEM
timezone is:
mysql> SELECT EXTRACT(HOUR FROM (TIMEDIFF(NOW(), UTC_TIMESTAMP))) AS `timezone`;
+----------+
| timezone |
+----------+
| 9 |
+----------+
Also, my linux system's timezone is:
$ date +'%:z %Z'
+09:00 JST
Now, when I insert a record to database, the created_at value will be utc time. For example:
# Now is 14:25:59
Product.create(name: 'Best')
# select created_at from products;
# 5:25:59
So if I test the feature with rspec in my spec source, I should get that data from database and plus 9 to equal the current system time. Is it good?
Why the data been saved as a utc time with active_record? If use this configuration, is there a way to test the database record in a right way?
Upvotes: 0
Views: 649
Reputation: 2280
The (maybe) best approach is to save all at UTC-Time. So Then you can use the Time.in_time_zone to get the time inside a specified zone.
My 20:00 PM is UTC 13:00 and maybe your 06:00 AM - but in the database its just the same time - UTC.
If it then comes to Rendering you use the rails helper for timing and always give the created_at.in_time_zone
.
If it comes to rendering you just throw out the UTC timestamp and let JavaScript to the rest, formatting the timestamp to the users local time.
Upvotes: 1