MySQL Date format and PHP

This is just a very quick blog entry to provide a little snippet of code and hopefully help some people.

I offer coding help and advice on several PHP forms for beginners to the language.  One of the common problems they have seems to be date/time stamps and MySQL format and handling.  This seems to be especially relevant to UK coders where our dates take the format dd-mm-yyyy whereas MySQL stores the date in yyyy-mm-dd HH:mm:ss.

PHP is a wonderful language that makes working with dates etc actually very easy.  To resolve the format of date/times from MySQL to a more UK centric format I created a very simple function

function mysql2uk($date) {
      return date('d-m-Y H:i:s',strtotime($date));
} 
<?php
function mysql2uk($date) {
 return date('d-m-Y H:i:s',strtotime($date));
} 
$sql ="select * from table";
$result = mysql_query($sql) or die();
$values = mysql_fetch_row($result);
echo mysql2uk($values['column']);
?>
And as easy as that your date is now in a UK format.

You can edit the format by changing the ‘d-m-Y H:i:s” part of the function and to save you having to have the function at the top of everyone of your pages you can put it in an include file and just include that file on your site/pages where you want the function available.

Hope this little snippet helps some.

Published by

admin

FC Software Technical Director