2

I have a model, called event, with a time attribute. I'm setting it to Time.now, and it I log the time on the object before save, its a second or two after the current time, as expected. But once the object is saved and then found in the database, the time is different, with a the date part being January 1st, 2000. What's causing this, and what can I do to make sure my times are saved correctly? EDIT: the column type is time, database is SQLite.

charleyh
  • 2,033
  • 2
  • 20
  • 32

1 Answers1

4

It sounds like you may be saving a time object rather than a date object.

Active record allows you to use time, date, and datetime objects.

If you are using a time or date object, however, they are still kind of (bad way of explaining it, see the linked response below for more details) full datetime objects. When you read them the date will be present on time objects (typically as January 1'st, 2000).


What can I do to make sure my times are saved correctly?

If saving / reading the full datetime is important for this field, you may want to consider changing the migration representing your model to use:

object.datetime

. . . rather than:

object.time

See this response for some more details: https://stackoverflow.com/a/3929047/1026898

Community
  • 1
  • 1
Ecnalyr
  • 5,792
  • 5
  • 43
  • 89
  • I don't think "they are still kind of full `datetime` objects" is accurate. If I create a date column with PostgreSQL it will be a date in Ruby and a date inside the database. – mu is too short Jul 26 '14 at 05:07
  • You're right. That's part of why I said it was a bad way of explaining it. It's a good amount of information that would have expanded the post unnecessary. That's why I added the link to a more descriptive answer. – Ecnalyr Jul 26 '14 at 05:08
  • But you still have three distinct types and I don't see where 2000-01-01 would come from. – mu is too short Jul 26 '14 at 05:10
  • There are a lot of variables to this problem that we can't see here that may be the specific issue causing this (different databases can vary in how they handle time-like values, for example). – Ecnalyr Jul 26 '14 at 05:14