I have requirement to save datetime (visited_at) attribute via api like POST localhost:3000/visit
, but the problem is I don't know how to handle time zone. I have see the explanation about rail time zone support here, but that when you create it through rails form. What I want to know if there is a way to handle this through my own api.
views:
162answers:
1
+1
A:
There are 3 related issues:
- Parsing incoming times (in your API)
- Storing time in your db
- Displaying time to your users
Your question is mainly about (1), but (2) and (3) are important as well.
For (2), I would normalize everything to UTC so daylight savings time, etc., won't effect you. In config/environment.rb, I would set ENV['TZ'] = 'utc'
just to play safe.
For (3), if you want to display time to the user in their local timezone, you'll have to store that in your User model and then format times appropriately.
Now, for (1), you should be able to parse the incoming time (using Time.parse, for example) and it will then be normalized into UTC. Time.parse can handle various ways of describing the time zone. (I would specify your API to state that if a time zone isn't specified, UTC is assumed).
E.g.
>> ENV['TZ']
=> "utc"
>> Time.now.to_s
=> "Wed Jan 13 16:43:00 +0000 2010"
>> Time.parse( "Wed Jan 13 16:43:00 +0500 2010" )
=> Wed Jan 13 11:43:00 +0000 2010
>> Time.parse( "Wed Jan 13 16:43:00 -0500 2010" )
=> Wed Jan 13 21:43:00 +0000 2010
>> Time.parse( "Wed Jan 13 16:43:00 EST 2010" )
=> Wed Jan 13 21:43:00 +0000 2010
>> Time.parse( "Wed Jan 13 16:43:00 CST 2010" )
=> Wed Jan 13 22:43:00 +0000 2010
>> t1 = "Wed Jan 13 16:43:00 CST 2010"
=> "Wed Jan 13 16:43:00 CST 2010"
>> t2 = "Wed Jan 13 17:43:00 EST 2010"
=> "Wed Jan 13 17:43:00 EST 2010"
>> Time.parse(t1) == Time.parse(t2)
=> true
Jason Yanowitz
2010-01-13 16:48:00
Thank you, you answer is exactly what I'm asking and this work like a charm on localhost, but on production it's not working I don't know why = =. I use javascript new Date() to send datetime to the site. This is its format "Fri Jan 15 2010 00:41:25 GMT+0700 (SE Asia Standard Time)". I tried to convert this to UTC to keep it in my db as you suggested by using Time.zone.parse() and it work very well on my localhost, but it's not on production.
art
2010-01-14 17:43:20
At this point, you're down to debugging the differences. Does it work in a production environment that runs on your development box (RAILS_ENV=production (with a database set up, etc., locally)? What's the differences between your production and development machines?
Jason Yanowitz
2010-01-15 21:11:02