In my experience, getting dates/times right when programming is always fraught with danger and difficulity.
Ruby and Rails have always eluded me on this one, if only due to the overwhelming number of options; I never have any idea which I should pick.
When I’m using Rails and looking at ActiveRecord datatypes I can find the following
:datetime, :timestamp, :time, and :date
and have no idea what the differences are or where the gotchas lurk.
What’s the difference? What do you use them for?
(P.S. I’m using Rails3)
The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you’re using.
Using MySQL as an example (if for no other reason because it’s most popular), you have
DATE,DATETIME,TIMEandTIMESTAMPcolumn data types; just as you haveCHAR,VARCHAR,FLOATandINTEGER.So, you ask, what’s the difference? Well, some of them are self-explanatory.
DATEonly stores a date,TIMEonly stores a time of day, whileDATETIMEstores both.The difference between
DATETIMEandTIMESTAMPis a bit more subtle:DATETIMEis formatted asYYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. WhileTIMESTAMPlooks similar when you fetch it from the database, it’s really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. BecauseDATETIMEstores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. AsTIMESTAMPonly stores the number of seconds since 1970-01-01, it uses 4 bytes.You can read more about the differences between time formats in MySQL here.
In the end, it comes down to what you need your date/time column to do:
DATETIME.TIMESTAMP.DATE.TIME.Having said all of this, Rails actually makes some of these decisions for you. Both
:timestampand:datetimewill default toDATETIME, while:dateand:timecorresponds toDATEandTIME, respectively.This means that within Rails, you only have to decide whether you need to store date, time or both.