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.
Asked
Active
Viewed 2,467 times
2

charleyh
- 2,033
- 2
- 20
- 32
-
1Which database? What is the column type? – mu is too short Jul 26 '14 at 05:08
-
If column type is Datetime and you saved `Time.now` it should work properly – Rajarshi Das Jul 26 '14 at 05:14
-
Please also give the column type, database adapter as suggested by @muistooshort – Rajarshi Das Jul 26 '14 at 05:15
-
If you post the migration for Event we can give you a more specific response. Your migration probably has `t.time: time` which you may want to change to `t.datetime` per my response below - but we can't be 100% sure until you show us. – Ecnalyr Jul 26 '14 at 05:17
-
Knowing what the "time" values look like inside the database would also be helpful. – mu is too short Jul 26 '14 at 05:36
1 Answers
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
-
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