PHP Format Any Time/Date for MySQL

April 20, 2005
Many people find the act of formatting a date or time for input into a MySQL database tedious. It's actually very simple. Here is a function that will take a timestamp value such as time() or a human readable string and format it for MySQL. MySQL format is: 'YYYY-MM-DD HH:MM:SS' The output of this little script would look something like:
2005-04-20 21:54:00
2000-09-10 04:30:00
2000-09-15 00:00:00
[code lang="php"]'; echo sql_date_format("10 September 2000 4:30 AM").'
'; echo sql_date_format("next Thursday").'
'; function sql_date_format($value) { // Very simple function to prepare a time/date value to // input into a MySQL database. Can accept both string // values as well as timestamps. // This function is used in my database class available // at http://www.micahcarrick.com/2005/04/19/php-mysql-database-class/ if (gettype($value) == 'string') $value = strtotime($value); return date('Y-m-d H:i:s', $value); } ?>[/code]

2 Comments about "PHP Format Any Time/Date for MySQL"

September 29, 2007 at 12:39 PM
I did not know that. I wrote this using PHP 4 and MySQL 4 some time ago. I'll look into that. Let's call this a simplifies solution for smaller-scale projects where as you mentioned, you know the behavior of the PHP and MySQL versions being used.
Uthman
September 29, 2007 at 12:13 PM
strtotime between php4 and php5 behavior differently; also the way older mysql stores datetime/timestamp (14) vs the new format YYYY-mm-dd HH:ii:ss, will cause further confusion if using strtotime. i would stay away from it unless i was sure the platform im developing on has the newest mysql and php

Leave a Comment about "PHP Format Any Time/Date for MySQL"

Your Name:
(Required)
Website URL:
(Optional)
Comment:
(No HTML. Newlines and URLs okay.)
Enter CAPTCHA:
 
 
 
 
Share