Convert UK style date to work with strtotime() function
By default the PHP function strtotime()
will take most date formats, and convert them to a Unix/Epoch timestamp.
However, as versatile as this function is, unfortunately, our planet (Earth) is not quite as succinctly set up.
One main problem is the difference in formatting between UK and USA dates. UK dates are typically formatted: dd/mm/yyyy, whereas USA uses: mm/dd/yyyy.
This becomes particularly confusing for PHP to interpret, as it’s not clear whether the following is 11th December or the 12th of November: 11/12/2014
PHP will assume this date 11/12/2014
to be American format, by default. Thus if you actually entered it as a UK date, your data is no longer incorrect.
This problem can easily be solved in a few ways:
Method 1:
The strtotime()
function will always assume an American format when the separator of /
is used. However if the dash separator (-
) is used, it assumes UK format:
<?php
$date = strtotime(str_replace('/', '-', '11/11/2014'));
?>
Method 2: Explicitly set the format and return a DateTime object.
<?php
$date = date_create_from_format('d/m/y', '27/05/1990');
?>
Method 3: Use a string operation to re-format:
<?php
$date = "31/12/2014";
$bits = explode('/',$date);
$date = $bits[1].'/'.$bits[0].'/'.$bits[2];
$date = strtotime($date);
?>
Method 1 should be the easiest solution for most uses, with method 2 being preferable if you want to return a DateTime object that can be better to work with if you need to do further adjustments.
Method 3 is the least preferred method but can be useful if your date format will need slightly more custom handling and manipulation before being converted to the date string format.