Dates in PHP and MySQL
3rd November 2006
I see a lot of people on forums and on my training courses asking about the best way (or any way) to manage dates stored in a MySQL database and used in PHP. Three options follow, but first the problem.
PHP uses unix timestamps for all its date functionality. It has methods to convert these timestamps into pretty much any text format you could want but internally it uses the timestamp format. A timestamp is simply an integer. Specifically, it’s the number of seconds that have elapsed since midnight on January 1st 1970 (greenwich mean time).
MySQL has three date types for use in columns. These are DATETIME, DATE, and TIMESTAMP. DATETIME columns store date and time as a string in the form YYYY-MM-DD HH:MM:SS (e.g. 2006-12-25 13:43:15). DATE columns use just the date part of this format – YYYY-MM-DD (e.g. 2006-12-25). TIMESTAMP columns, despite their name, are nothing like the unix timestamps used in PHP. A TIMESTAMP column is simply a DATETIME column that automatically updates to the current time every time the contents of that record are altered. (That’s a simplification but broadly true and the details are not important here). In particular, since version 4.1 of MySQL the TIMESTAMP format is exactly the same as the DATETIME format.
So the problem is how to work with these two very different date formats – the PHP timestamp integer and the MySQL DATETIME string. There’s three common solutions…
One common solution is to store the dates in DATETIME fields and use PHPs
date()andstrtotime()functions to convert between PHP timestamps and MySQL DATETIMEs. The methods would be used as follows -$mysqldate = date( 'Y-m-d H:i:s', $phpdate ); $phpdate = strtotime( $mysqldate );
Our second option is to let MySQL do the work. MySQL has functions we can use to convert the data at the point where we access the database.
UNIX_TIMESTAMPwill convert from DATETIME to PHP timestamp andFROM_UNIXTIMEwill convert from PHP timestamp to DATETIME. The methods are used within the SQL query. So we insert and update dates using queries like this -$query = "UPDATE table SET datetimefield = FROM_UNIXTIME($phpdate) WHERE..."; $query = "SELECT UNIX_TIMESTAMP(datetimefield) FROM table WHERE...";Our last option is simply to use the PHP timestamp format everywhere. Since a PHP timestamp is a signed integer, use an integer field in MySQL to store the timestamp in. This way there’s no conversion and we can just move PHP timestamps into and out of the database without any issues at all.
Be aware, however, that by using an integer field to store your dates you lose a lot of functionality within MySQL because MySQL doesn’t know that your dates are dates. You can still sort records on your date fields since php timestamps increase regularly over time, but if you want to use any of MySQL’s date and time functions on the data then you’ll need to use FROM_UNIXTIME to get a MySQL DATETIME for the function to work on.
However, if you’re just using the database to store the date information and any manipulation of it will take place in PHP then there’s no problems.
So finally we come to the choice of which to use. For me, if you don’t need to manipulate the dates within MySQL then there’s no contest and the last option is the best. It’s simple to use and is the most efficient in terms of storage space in the data table and speed of execution when reading and writing the data.
However, some queries will be more complicated because your date is not in a date field (e.g. select all users who’s birthday is today) and you may lose out in the long run. If this is the case it may be better to use either option 1 or 2. Which of these you use depends on whether you’d rather place the work on MySQL or PHP. I tend to use option 2 but there’s no right or wrong answer – take your pick.
So to summarise, for those who’ve skipped straight to the last paragraph, most of the time I use option 3 but occasionally I use option 2 because I need MySQL to know the field contains a date.

29 Comments add your own
This is really a great article. Nicely stated, lots of imformation given clearly. Thanks!
Greg | 6th December 2006 at 17:53
Good article. I am also trying to decide what to use and what not to.
Sohail Abid | 8th December 2006 at 15:05
Useful article
Many Thanks
But is there any function in php which can convert number of seconds back to datetime format
Atif | 2nd January 2007 at 17:02
If by number of seconds you mean a unix timestamp, then just use the date() function –
date( 'Y-m-d H:i:s', $timestamp )richard | 2nd January 2007 at 17:18
One thing to bear in mind when using UNIX timestamps is that they always start at 1/1/1970. Some UNIX/MySQL implementations (and my Fedora 6 seems to be one of them) cannot store pre-1970 dates, and these always come out as 0 (rather than a negative integer). For this reason, I have moved towards the MySQL DATE type and do the string conversion manually.
Dan Walker | 6th January 2007 at 13:12
Thanks Dan. That’s something I should have mentioned above.
richard | 6th January 2007 at 16:00
Very cool article. I think a nice addition would be getting dates from mysql and displaying them using php formatting functions. I’ve pretty much got it figured out. But you may be able to explain it better than a lot of the other resources I’ve found for displaying dates in a user-friendly format. Thanks!
Joey | 19th March 2007 at 02:35
man……….u dont know how helpful u have been…..
i was fxxxxxg frustrated due to confusion of timestamp……….was abt to break my laptop……but then i found ur article…….and the problem was solved in a min…….thx buddy…
Babu | 4th May 2007 at 03:28
Very well written article! clear and simple! Thanks for publishing!
Leandro | 9th May 2007 at 17:44
I just wanted to say, thanks for a great article, has helped me heaps!
Nick | 30th May 2007 at 10:00
I have created a website to help format mysql dates.
http://www.mysqlformatdate.com
mysq format date | 6th January 2010 at 11:54
hi,
i have a record in a mysql table with a timestamp colum. i wan tot:
1) find a record within the last 24 hours.
2) some how do a calculation on (1) to add 24hrs to this recrd and subtract the time now and display the calculated time on screen via php.
ie. the requirement is to tell user/php how long before another record can be inserted since the last entry.
i can do (1) but dont know how to do 2. any help is appreciated.
thanks.
alan | 6th January 2010 at 17:54
More than 3 years later, thanks a lot
It was really helpfull !
Integrateur html | 19th January 2010 at 09:43
Just wanted to correct one thing — unix timestamps are signed integers, which is why they run out in 2038. An unsigned integer would last into the next century.
Mike | 26th February 2010 at 18:36
Thanks Mike. I’ve corrected the article.
Richard | 27th February 2010 at 11:52
Extremely helpful article! I’ve spent close to 2 hours trying to figure out this problem concerning time, and your article pointed me to exactly what I was looking for! I used the FROM_UNIXTIME() MySQL functionality to achieve my results.
Once again, thank you very much for this article!
Nic Anderson | 10th March 2010 at 08:38
Best, most concise guide to PHP/MySQL date management I’ve found. Thanks a bunch!!!
Jeff Jackson | 29th March 2010 at 16:39
Wow!! Great, nice article. It’s very helpful. Thanks a lot
Kelvin Barret | 15th April 2010 at 05:39
MySQL column type is datetime
When inserting a record using $mysqldate it saves the date time like this: 1970-01-01 01:00:00 and $phpdate like this: 0000-00-00 00:00:00
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
$phpdate = strtotime( $mysqldate );
How do I get the date time from right now?
Theo | 20th April 2010 at 13:01
$mysqldate = date( 'Y-m-d H:i:s', time() );Richard | 20th April 2010 at 17:50
I still have found an answer to what I’m trying to do:
On a form, a user is entering a purchase date, not necessarily the current date, say 4/15/2010. How do I convert this to either a PHP date or a mysql date???
Cheryl | 28th April 2010 at 15:53
@Cheryl:
When you got the day, month and year stored in variabeles. You could use the php mktimefunction() to convert into a php (UNIX) date.
Peter | 10th June 2010 at 14:08
I got a date exported from an application which is represented by integer numbers. e.g.
2048738713 which is Dec 25, 1442
As this represents a date before 1970, does anyone know how this is achieved (or calculated)?
afatac | 11th June 2010 at 11:30
[...] questo mio articolo prendo spunto da un post di Richard Lord, datato 2006 ma ancora valido (basta vedere le date dei commenti). L’argomento affrontato รจ [...]
Gestione di date con PHP, MySql, e jQuery UI Datepicker »looking for my namespace | 12th June 2010 at 23:26
I made some simple functions (“helpers”) for CodeIgniter to make it even more simple to convert between the two…
http://shinytype.com/php/codeigniter-php-time-to-mysql-datetime-helper/
Thanks!
Dave Rogers | 23rd June 2010 at 08:36
You should check out Zend_Date (http://framework.zend.com/manual/en/zend.date.html)
Brad Hafichuk | 8th July 2010 at 18:54
I’m using this string
$oDate = strtotime($row['CompletedIT']);
$sDate = date(“d/m/y”,$oDate);
echo $sDate
to get the MYSQL date value stored in the table row ‘CompletedIT’.
The database value is 2010-07-22 but I get the echo return of 01/01/70
Can someone give me an idea as I want to display the date as dd/mm/yyyy
Thanks in advance
Pete B | 22nd July 2010 at 16:21
Hi Pete,
You can use the function DATE_FORMAT()
This example picks the postdate column
I think what you want is
SELECT DATE_FORMAT( `postdate` , ‘%M %D, %Y’ ) AS `theDate`,
I think what you want is
SELECT DATE_FORMAT( `postdate` , ‘%M/%D/%Y’ ) AS `theDate`
(untested though should work)
Regards,
Daniel
Daniel Redfern | 28th July 2010 at 08:53
This is a better way
date (‘d / M / Y’, strtotime($row['mysql_date']))
2010-10-10 = 10 / Oct / 2010
xxx
Andrew Wood | 18th August 2010 at 09:57
Leave a Comment comment policy
XHTML: you can use these tags - <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>Subscribe to the comments via RSS Feed