Colin Law wrote:
> I would suggest changing the fields to DateTime.  Then you will be
> able to do direct comparisons.

>From someone who has been burned by this in the past, I have a slightly 
different suggestion.

If you actually do need to store a time that is independent of a date, I 
would recommend storing time as an offset. Something like seconds from 
midnight. Store this value as an integer in the database.

Using such a technique eliminates dependency on the geo-political rules 
governing the representation of dates and times.

For convenience you could add an instance method to give you the time of 
day as a string.

# Assume the "time_offset" column contains 25000 (seconds from midnight)
def presentable_time
  t = Date.today.to_time + self.time_offset.seconds
  t.strftime("%I:%M %p")
end

puts my_object.presentable_time
=> "06:56 AM"

With this technique your "difference" or "duration" calculations become 
trivial:

time_diff_seconds = obj_1.time_offset - obj_2.time_offset

It's not that common that one needs to store time independently of date. 
However, one case that comes to mind would be if you were calculating 
statistics based on time of day. Maybe you would want a graph showing 
activity based on the time of day. If you're doing something like that 
then having the time of day stored separately from the date would 
simplify the queries.

select * from orders where time_offset between 46800 and 54000;

would select all orders placed between 1:00 PM and 3:00 PM
-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to