strtotime for non-US (e.g. UK) dates

16 03 2009

Not a big novelty here, but I figured I’d show you what I did.

I’m working on an application for the UK market, and we have a number of date fields in the form. The previous Indian programmer took the easy way out and used text fields in the database to store the dates. When I added some more fields, I used the appropriate date/time field type, and had to store and retreive them appropriately.

The form uses a date picker taken from HTMLGoodies.  The prior version used another script which wasn’t working well, although it allowed for named months which removed any locale convention confusions. This date picker uses numeric dates, and allows for the UK “day/month/year” convention. Getting that into (and out of) MySQL is another story.

The “out of” is easy actually. Take a date and format it:

date('m/d/Y',strtotime($date)))

Before I did that, however, I wanted to test to see if the date was empty. Using empty() didn’t work, since MySQL returns an empty date as 0000-00-00, so I made another function:

function emptyD($d){
  return ($d=='0000-00-00')?true:empty($d);
}

Using strtotime, however, misinterprets the UK date format from the user, and cannot directly create a MySQL-ready date. Using the following function, quickly found at this Polish site, reformats the date from d/m/Y to m/d/Y using regular expressions (smart!).

function strtotime_uk($str)
{
  $str = preg_replace("/^\s*([0-9]{1,2})[\/\. -]+([0-9]{1,2})[\/\. -]*([0-9]{0,4})/", "\\2/\\1/\\3", $str);
  $str = trim($str,'/');
  //echo "Converted to UK date: $str<br>";
  return strtotime($str);
}

and formated for MySQL using

date("Y-m-d H:i:s", strtotime_uk($_POST['emp1_start']))