I usually store dates as integers using PHP’s time() function in a MySQL database rather than using MySQL’s date format simply because it’s easier to manipulate when I pull it back out, but are there any disadvantages to this?
I usually store dates as integers using PHP’s time() function in a MySQL database
Share
Range:
There’s always the obvious disadvantage: The range that you can store is limited från 1970 to 2038. If you need to store dates outside of this range, you’ll generally need to use another format. The most common case I’ve found where this apply is to birthdates.
Readability:
I think that the most important reason that people chose to use one of the built-in date-types it that the data is easier to interpret. You can do a simple select, and understand the values without having to format the response further.
Indexes:
A good technical reason to use the date types is that it allows for indexed query in some cases that unix timestamps doesn’t. Consider the following query:
If mydate_field is of a native date type, and there’s an index on the field, this query will actually use an index, despite the function call. This is pretty much the only time that mysql can optimize function calls on fields like this. The corresponding query on a timestamp field won’t be able to use indices:
If you think about it for a bit, there’s a way around it, though. This query does the same thing, and will be able to use index optimizations:
Calculations:
Generally, I store dates as unix time, despite the disadvantages. This isn’t really based on it’s merits, but rather it’s because I’m used to it. I’ve found that this simplifies some calculations, but complicate others. For example, it’s very hard to add a month to a unix timestamp since the number of seconds per month varies. This is very easy using the mysql DATE_ADD() function. However, I think that in most cases it actually simplifies calculations. For example, it’s quite common that you want to select the posts from, say, the last two days. If the field contains a unix timestamp this can be done easily by simply doing:
It’s probably a matter of taste, but I personally find this faster and easier than having to rember the syntax of a function such as DATE_SUB().
Timezones:
Unix timestamps can’t store time zone data. I live in sweden which has a single timezone, so this isn’t really a problem for me. However, it can be a major pain if you live in a country that spans multiple timezones.