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 are 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.

74 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
Do you guys know why the NOW() function creates a default date like this: YYYY-MM-DD when the common U.S date format is DD-MM-YYYY?
Can the default just be changed to be Americanized in format?
Thanks!
San Francisco Hiking | 10th September 2010 at 00:24
[...] Continue… [...]
Dates in PHP and MySQL « 8thPerson's CreativeCraze | 15th September 2010 at 15:11
Hey thanks – good information, This really helped when trying to organize a search result by date that i built. I didn’t realize without a some sort or method in my case this one to accurate pull search results organized by date out of a mysql database.
Thankz Richard!
Doran Baker | 18th September 2010 at 09:49
Wow i better check my spelling better next time. Sorry about that everyone.
Doran Baker | 18th September 2010 at 09:50
One big issue that this discussion leaves out in determining what approach is best, is the issue related to differences in PHP and MYSQL in regards to timezones, and specifically if the timezone of the mySQL server and the PHP server are different (common in a highly distributed web app), or both may be in the same timezone (or same computer), but each server app may not have environment or configuration settings correct for the timezone (in which case all date and time functions may be returning times in the incorrect timezone or in UTC format), or when your server switches timezones (perhaps you move your site to a new host in a different timezone, then all your previous datetimes stored in mysql may be incorrect.).
Take care to spend some time researching best practices and patterns for php, mysql and timezones. In short, it is usually best to store datetime data consistently in a specific (app and server neutral) timezone throughout your app, and then convert datetimes to the current users timezone as required.
Here are some good links:
http://dev.mysql.com/doc/refman/5.0/en/timezone-problems.html
http://jokke.dk/blog/2007/07/timezones_in_mysql_and_php
R'phael Spindel | 4th October 2010 at 08:20
Great article!
How would I convert a mysql table column which is storing characters (varchar) in UK date format (dd/mm/yyyy) to a mysql date column? I want to keep the data valid and there are about 16000 rows to change.
Thanks in advance.
Rich
Rich Senior | 8th October 2010 at 14:49
2 Small lines of code solves such a BIG TROUBLE!
THAKS A LOT for that little but VERRY usefull code
It saved me more than one time
General Bison | 18th October 2010 at 10:15
I was searching for the best way to add dates in MySql and PHP. This article provided a solid over. Thx, Richard
Richard Cummings | 25th October 2010 at 15:05
Finally! I’ve been trying to convert an RSS pubDate to mysql timestamp after using strtotime() and the missing function was FROM_UNIXTIME(). had to surf many pages to find this. thanks!
Ilene | 1st December 2010 at 22:45
[...] Dates in PHP and MySQL. Leave a Comment LikeBe the first to like this [...]
Dates in PHP and MySQL « Mike's Article Bin | 19th December 2010 at 19:45
Good article but it doesn’t deal with what date ranges can be stored.
What if I want to store a date of 1st January 1854??
I can’t use a timestamp.
Donald | 2nd January 2011 at 17:02
I think a newbie should be cautious when choosing the third solution. You never know how things can change and one day you can regret your choices. This is like marriage.
devil advocate | 5th January 2011 at 12:18
An easier way to go would be to use the MySQL timestamp in the database itself with no code required whatsoever:
“INSERT INTO `table` SET `date` = CURRENT_TIMESTAMP”
Then, the MySQL to PHP code would be as stated:
$date = date(“m/d/Y”, $data['date']);
Makes it easier than converting from PHP INTO the MySQL table if you’re just going to use MySQL’s format anyway. Also, if you ever change the format in MySQL that the table uses, you don’t have to update your INSERT statements.
Nate | 11th January 2011 at 17:52
Thanks for the great tips. This has helped me wwith the timestamp issue in conjuction with PHP.
To add my two cents to the comments here.
@San Francisco Hiking | 10th September 2010 at 00:24
MySQL stores these values in the YYYY-MM-DD HH:MM:SS format for sorting. If you use the US format the dates will be sorted by days instead of years
ie: (first 2 days of october, november & december)
US
01-10-2010
01-11-2010
01-12-2010
02-10-2010
02-11-2010
02-12-2010
@R’phael Spindel | 4th October 2010 at 08:20
Most servers give the option to run the daemon in custom time-zones. ie: you can run a php enabled webserver with the US-Timezone while the server is running in AMS-IX (amsterdam). This is very helpfull when working with distributed servers and backends.
Oguzhan | 8th February 2011 at 00:06
i am inserting date in mysql as now() function. but it is taking server date. instead i want the date should be in india timezone according. please suggest.
jalandhar college | 9th February 2011 at 14:15
Thanks for this primer on dates in PHP and MySQL. I know them pretty well but always find myself returning to valuable references such as this.
–Richard
Richard | 14th February 2011 at 17:17
Hi,
Using jquery datepicker,I have the format of the date returned from Datepicker as (yy-mm-dd) which returns the string as 2011-04-22.
When I want to INSERT it in the MySQL table in the column with datatype as DATE, I get 0000-00-00 saved. Browsing through SO, I found suggestions about FROM_UNIXTIME, but this gives me the date as 1970-01-01.
Any help ?
ishan | 11th April 2011 at 09:23
This article worked fine for dates in the near future, but I struck issues with dates past 2038.
Do any of the options above work with dates with a year greater than 2038?
If not, how do you propose we manage dates greater than 2038?
Thanks,
Neil
Neil | 27th April 2011 at 03:55
SELECT DISTINCT FROM_UNIXTIME(starttime,’%Y-%m-%d’) as starttime,type FROM `agenda` WHERE id_users=’1315907789′ AND (starttime>=’1291141800′ AND starttime=’1291141800′ AND endtime<='1293820199') ORDER BY starttime
jay | 3rd May 2011 at 12:25
Format prob.
code:
mysql_query(“INSERT INTO movies (DiscFormat, Date)VALUE (‘”.$DiscFormat.”‘,DATE_FORMAT(NOW(),%d/%m/%Y) )”) or die (mysql_error());
gives: 2011-05-20 13:32:16 and it completely ignores the %d/%m/%Y format or any other for that matter…
What I want is: 20-05-2011 13:32:16
…and yes I do realize that the %d/%m/%Y format gives only the date not date and time.
I’ve tried different variations with the date_format but always the same default format or just plain nulls…
-cheers
spinster | 20th May 2011 at 11:51
[...] Thanks here [...]
Translating and Formatting MySQL dates in PHP « Technoblog | 21st May 2011 at 01:57
spinster
MySQL’s DATE_FORMAT function can’t be used to alter the format of the data in the table – dates are stored inone specific format only. This function is intended for altering the format of the data when it is pulled form the table. i.e.
SELECT DATE_FORMAT(Date,%d/%m/%Y) FROM movies
Richard | 21st May 2011 at 10:38
Regarding dates after in 2038 and thereafter, you should be able to do something like this (at least that is what I’ve used), if you are using PHP 5.2 or later, iirc:
$dateTime = new DateTime("now", new DateTimeZone('America/New_York'));
$mysqldate = $dateTime->format("Y-m-d H:i:s");
echo $mysqldate;
Obviously adjust for your time zone.
Chris R | 23rd May 2011 at 22:23
HI,
i have a MYSQL database, in the table nEventlog, the datetime is stored in second in the column ndatetime.
How can i convert the datetime in second (format) to YYYY/MM/DD HH:MM:SS (format) ?
i know in mssql query its ((CONVERT([varchar](50),getdate(),(103))+’ ‘)+CONVERT([varchar](50),getdate(),(8))).
Can you please help ?
many thanks
laurent | 24th May 2011 at 18:11
[...] You can take their input and use strtotime(); Also, When inserting and selecting the date you can use MYSQL to do that.. $query = "UPDATE table SET datetimefield = FROM_UNIXTIME($phpdate) WHERE…"; $query = "SELECT UNIX_TIMESTAMP(datetimefield) FROM table WHERE…"; so they would enter a date: 01/29/2011 and you would use strtotime which would return a unix timestamp. which you can then insert and select to/from the db using the example query above. Then you can use date(FORMAT,$mysqldate); where $mysqldate is the date field from the SELECT query above. Dates in PHP and MySQL [...]
convert user's entered date format into mysql date format - Hot Scripts Forums | 26th May 2011 at 00:05
I’m trying to understand this, but I’m php retarded. I’ve done this,
$today = date(‘Y-m-d’);
$expires = date(‘Y-m-d’, strtotime(“+90 days”));
$warn = date(‘Y-m-d’, strtotime(“+83 days”));
when I put these into my database, the only part that gets stored is the year, so, I get 2011 in all three fields. which doesn’t help me at all.
How do I get the php to insert the WHOLE date into the database? I want to keep it as YYYY-MM-DD format.
Zenning | 10th June 2011 at 17:52
Amazing article! Helped me solve my own php to mysql conversions. Thanks a million Richard!
soulex | 16th June 2011 at 04:14
One of the most simple way…
$date = date_create(’2000-01-01′);
echo date_format($date, ‘d-m-Y H:i:s’);
Ayesha | 5th July 2011 at 06:26
Regards option 1., the following won’t work with mixed US/UK timezones:
$phpdate = strtotime( $mysqldate );
since the month/date swaps around.
Instead, one solution (if you want code to run on PHP < 5.2.0) is as follows:
list($y, $m, $d) = split('[/.-]', $mysqldate);
$phpdate = mktime(0, 0, 0, $m, $d, $y);
PhilRoach | 10th August 2011 at 12:44
@Zenning:
“when I put these into my database, the only part that gets stored is the year, so, I get 2011 in all three fields.”
Post your sql. The php part looks right.
Alan | 29th September 2011 at 03:24
I’ve used the truncante – trunc(date) but php returns an error. Do I’ve to alter the date field to Date instead of DateTime to avoid the hh:mm:ss bit.
lutsam | 6th December 2011 at 11:14
I am always scared when I read articles like this. How can anyone recommend storing a unix timestamp in a database table? What if you have to switch to a different programming language one day? What happens after 2038?
Your data almost always outlives the application. Just store them as they are supposed to be stored and don’t let limitations of a programming language influence database data type decisions.
mo | 19th December 2011 at 16:25
important hint:
You must not mix solutions 1 and 2. php functions and mysql functiond differ by 24 sec (at present). Check it by comparing the results of strtotime(a datetime) and UNIX_TIMESTAMP(same datetime).
Explanation is found here: http://pumka.net/2010/10/24/why-mysql-timestamp-is-24-seconds-different-from-php/
Mathias | 13th January 2012 at 13:46
That looks quite nice, but I was wondering if there was a way one could change the default settings in MySQL so that the data format automatically saves in British format.
Helen Neely | 24th January 2012 at 15:40
How would I use Richard’s example above,
$mysqldate = date( ‘Y-m-d H:i:s’, time() );
to get the future date and time, for example I want to add 30 days in the future. thanx,
Jose | 12th February 2012 at 22:13
This article is super helpful, thanks for posting, I think i’ll go with your recommended mysql datetime method.
Josh | 24th February 2012 at 09:22
[...] This means that using a mySQL function like NOW() generates a Texas timestamp rather than a London timestamp which isn’t what I want. There are a number of solutions to this problem, Richard Lord has written a good, clear post about possible solutions on his blog. [...]
Keeping PHP and mySQL dates in sync « cotsweb.com Blog | 16th May 2012 at 16:55
[...] I am following http://www.richardlord.net/blog/dates-in-php-and-mysql [...]
Dates in PHP and MySQL • PHP Help Coding Programming | 2nd June 2012 at 19:58
[...] I found it here: http://www.richardlord.net/blog/dates-in-php-and-mysql Rate this:Like this:LikeBe the first to like this post. Categories: DataBases, MSSQL, MySQL [...]
DB Insert IDs and PHP times « EvoDynamic | 7th June 2012 at 17:25
I just wanted to add Date instead of datestamp… can you help me plz
fysisoft | 2nd July 2012 at 16:27
Just wanted to know: What should be the size of the int column of the mysql table where I’ll be storing the timestamps generated from php. The maximum size is 60, but I want the most optimized size to make database more memory efficient. Thanks and great post.
zusk | 9th July 2012 at 19:24
@zusk It would be an unsigned int – 4 bytes long
Richard | 10th July 2012 at 12:30
How can i compute the difference of an sql date (say 2012-01-13 12:29:09) to the date today(2012-08-04 12:29:09)? thanks..
clarizza | 4th August 2012 at 08:41
Datetime is internally a 64 bit integer that operates a lot like the “unix time” (seconds from epoch). It’s stored as seconds from 1000-01-01. Datetime is in no way shape or form a string… Otherwise indeices against it would be stupidly inefficient. Doing WHERE tbl1_time = ’2012-01-01 00:00:00′ is like integer comparison (other than the parsing step for the input date, which isn’t too bad).
Obviously PHP sees it as a string, but you can easily remedy that by casting it back using strtotime.
Harlan Sanders | 6th November 2012 at 19:57
[...] http://www.richardlord.net/blog/dates-in-php-and-mysql This entry was posted on Wednesday, January 30th, 2013 at 7:16 pmand is filed under web. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]
php and mysql time conversion | code@butterflybone | 30th January 2013 at 11:16
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