Dates
Whilst you could store a date as a text string, MySQL has more optimal ways of storing dates!
TIMESTAMP
One perfectly valid way to store dates would be as a timestamp. A timestamp is a 10-digit representation of the number of seconds since the Unix epoch of 1st January 1970. This could be stored as a CHAR column, requiring 10 bytes storage, but the most optimal data type is the numeric INT(UNSIGNED) type, requiring just 4 bytes storage.
Timestamps are particularly useful if you’re using PHP, as the date() function will display them in your chosen format and you can calculate dates by adding or subtracting a number of seconds (86400 is equivalent to 24 hours etc…).
One drawback of using timestamps is that they’re not human readable straight from the database. Would you know what date 1262986313 refers to? Another is that due to the 10-digit length, timestamps may have problems at 3:14:07AM on 19th January 2038 when the value 9999999999 is reached!
DATETIME
The DATETIME data type is designed specifically to store both the date and time as 2010-01-08 15:00:00 (for example).
One disadvantage is that this requires 8 bytes storage – double that of a timestamp.
- Firstly dates stored using DATETIME are human-readable straight out of the database. So if you’re browsing your data with php MyAdmin you can see what your dates actually mean!
- Secondly MySQL has a whole host of built-in functions to work with native DATETIME formats. You can add and subtract dates, calculate the difference between dates, output the date in your preferred format and much more using MySQL alone and without involving additional PHP (for example) scripting.
- And finally, if you really want to output your DATETIME column as a timestamp, MySQL has a built-in function to do that, too!
Note that MySQL can also store the year alone, the date alone and a number of related types.