May 16, 2008
PHP: Formatting dates
Formatting dates can be tricky for the beginning PHP programmer, here’s a few simple examples that will get you started. I’ll go over how to convert from database date formats to traditional date formats and back again, as well as how to test a date using regular expression matching…
When your input is from a database field
$date = '2008-05-16'; $datetime = '2008-05-16 21:49:30'; $fdate = date('m/d/y',strtotime($date)); //yields: "05/16/08" $fdatetime = date('m/d/Y h:i:s a',strtotime($datetime)); //yields: "05/16/2008 02:49:37 pm"
The strtotime() function converts your date or datetime into the very versatile unix timestamp . The date() function formats the unix timestamp into a multitude of styles.
When your input is from a user
You know you can’t blindly trust user date coming from forms, that’s why it’s a good idea to test for the right format before inserting data, including dates. Use a regular expression to test the date field.
$date = $_POST['input_date']; $pattern = "/^[0-1]?\d{1}[\/.-][0-3]?\d{1}[\/.-](\d{2}|\d{4})$/"; //test for a valid date if (preg_match($pattern, $date)) { // go on and submit your form ... } else { //send back an error message echo "Your date was not in a valid format."; }
When you want to prepare a date to be inserted into a database
$date = '05/16/2008'; $fdate = date('Y-m-d',strtotime($date)); //yields: "2008-05-16" $fdatetime = date('Y-m-d H:i:s',strtotime($date)); //yields: "2008-05-16 00:00:00"
