views:

49

answers:

2

I have the following entry in my database:

t.time :my_time_stamp

In my controller I update it like this:

model.update_attributes(:my_time_stamp => Time.now.utc)

I can see that I'm writing:

Mon 9 November, 8:54.54 UTC 2009

However, when I later read this value I get:

Sat Jan 01 08:54:54 UTC 2000

It seems that the time part has been stored but not the date part. I'd expect that because it's a time field, but why do I end up storing and retrieving a date? I guess I must be misunderstanding how this works in some fundamental way.... what am I doing wrong?

What I need to do is calculate the time in seconds since the update to the database.... is there an easier way to do this?

Thanks!

+5  A: 

A "time" field is storing only the time. Not the date.
So it's logic for you to get only a valid time and not a valid date.

If you wish to store date and time in the database, you should have the following migration :

t.datetime :my_time_stamp
Damien MATHIEU
I thought that, but I'm confused. Doesn't time.now return a 'time' which is stored in the 'time :my_time_stamp' field, and when I later query it with model.my_time_stamp shouldn't I also get a time....?
cmaughan
Yeah but in the database you store only the time. So you don't get the date back.
Damien MATHIEU
yes, that's my point... if I do model.my_time_stamp then why is the 'type' of the returned value a date....? Is it possibly because the database is really storing a datetime object? If in the rails console I do :model.update_attribute(:my_time_stamp, Time.now.utc), then I print model.my_time_stamp it looks like a date.....
cmaughan
Yeah because the Time object can store the date. But you should have a Time object, not a Date one. You can check that with doing something like `<%= model.my_time_stamp.class.to_s %>` which should show you that you have a Time object and not a DateTime one.
Damien MATHIEU
+2  A: 

Ruby does not have a dateless time object, so it converts the dateless time field in your database to that time on some arbitrary day. Ruby's Time objects encode a number of seconds since the unix epoch, so they include the date. The correct way to store them in the database is with a datetime field, or if you prefer, you could use an integer field and store Time.now.to_i.

mckeed