Best practice for storing the date in MySQL from PHP Best practice for storing the date in MySQL from PHP mysql mysql

Best practice for storing the date in MySQL from PHP


If you store dates as Unix timestamps in the database, you're giving yourself the heavy lifting. You have to convert them to the formats you want to use, you have to do the calculations between date ranges, you have to build the queries to get data in a range. This seems counter-intuitive- surely your "programmer time" is best spent solving real problems?

It seems much better practice to store dates and times in the proper format that MySQL has available, then use the database functions to create the queries for the data you want. The time you would waste doing all the convertions and mucking about is massive compared to the afternoon spent reading (and understanding) 11.6 MySQL Date and Time Functions


I've also been a huge fan of the unix timestamp all my life. But I think the correct answer is: "depends". I recently did a single table database where I wanted to only list URLs. There would be a date field, but the date field is purely for sorting. I.e order by last_crawled. Which means I will never use any built-in date functions on that field. It is merely an easy way to get the oldest entries first and I will never apply date functions to this field. Now, had I made this a date field, I would have lost out on two things:

  1. A datetime field is twice the size of an integer
  2. Sorting by an integer is faster (not 100% sure of this, pending outcome of this question)

However, for another system I had to store transactional information. This made using internal mysql date functions possible which turned out to be very useful when we had to start doing reports.


One advantage of using the MySQL date/time types is to be able to more simply use the date/time functions in MySQL.

The DATE type also has the advantage in that its only storing day, month and year so there is no space wasted or comparison complication that a seconds since epoch time would have for situations where you only cared about the day and not the time.

Personally I tend to use a database as just a dump for data so such functions are of little interest. In PHP I tend to just store the date in integer format for pretty much the reasons you state.