Best way to save datetime via api in rails
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 开发者_C百科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.
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
精彩评论