Home > Tech > Coding > PHP strtotime Bug Workaround

PHP strtotime Bug Workaround

If you’re not into coding in PHP, skip this post and read the next one.

A few months ago, I was working on some PHP code and found a bug in the strtotime function in PHP version 4.3.11. It’s been fixed in version 5.2.0 but I’ve created a workaround fix for people using the older version of PHP.

Strtotime is a function that converts strings into time. The strange bug shows up when subtracting 2 from Sunday, which should give you the date of 2 Sunday’s prior to the original date.

The code below shows the same code running on both versions:

$datefmt = 'n/j/Y';
echo 'Current PHP version: ' . phpversion()."";
$offset = time();
echo "today=".date($datefmt, $offset)."<br />";
$s = strtotime("-2 Sunday", $offset);
echo "-2 sunday timestamp=".$s."<br />";

$d = date($datefmt, $s);
echo "-2 Sunday=".$d."<br />";

$sunday = strtotime("last Sunday", $offset);
$lastsunday = mktime(0, 0, 0, date("m", $sunday), date("d", $sunday)-7,   date("Y", $sunday));
$d = date($datefmt, $lastsunday);
echo "fixed -2 sunday=".$d."<br />";

The output from the code above is shown below when using PHP 5.2.0:

Current PHP version: 5.2.0
today=4/14/2009
-2 sunday timestamp=1238914800
-2 Sunday=4/5/2009
fixed -2 sunday=4/5/2009

The output from the code above is shown below when using PHP 4.3.11:

Current PHP version: 4.3.11
today=4/14/2009
-2 sunday timestamp=-1
-2 Sunday=12/31/1969
fixed -2 sunday=4/5/2009

The error is shown in yellow highlight. You can see that the error starts with the timestamp being “-1” in the older version. Hope that helps somebody out there.