How to fix strtotime() returning wrong values for different date formats in PHP?

I had a little problem with strtotime()  function in the past because (as some people have pointed out) you can’t really set a locale for strtotime. If you’re American, you see 11/12/10 and think “12 November, 2010”. If you’re Australian (or European), you think it’s 11 December, 2010. If you’re a sysadmin who reads in ISO, it looks like 10th December 2011.

The best way to compensate for this is by modify your joining characters. Forward slash (/) represents American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.

Please observe following example:-

echo date("jS F, Y", strtotime("11.12.10")); 
// outputs 10th December, 2011 

echo date("jS F, Y", strtotime("11/12/10")); 
// outputs 12th November, 2010 

echo date("jS F, Y", strtotime("11-12-10")); 
// outputs 11th December, 2010

All the 3 lines of code above returns a different value according to the format of date you pass to the strtotime() function. Now if you want to standardise your code you can use any one of these formats and convert other date format to the particular one that you’re comfortable with.

Here is simplified solution to convert date & time formats :-

$date = '11/12/2010';
$date = str_replace('/', '-', $date);
echo date("jS F, Y", strtotime($date));
// outputs 11th December, 2010

Hope this helps someone!

2017-09-27T09:45:06+00:00 By |PHP Tips|