Home > Tech > Coding > PHP strtotime Bug Workaround – Part 2

PHP strtotime Bug Workaround – Part 2

Back in 2009, I noticed a minor bug in PHP 4.3.11 that caused a problem with obtaining the “last” Sunday using the strtotime function and provided a workaround fix.

However, as of PHP version 4.4.9, that fix no longer works. I didn’t really dig into why that is, but did create a function that works for that version and above as shown below.

To use, simply call get_sunday with no parameters to get the last Sunday from today. To use another day, provide $offset. $datefmt is a global variable that is the date format that is to be used to return the date of Sunday.

function get_sunday($offset = FALSE) {
   global $datefmt;

   if (!$offset)
      $offset = strtotime(date($datefmt));
      $offset = strtotime($offset);

   if (date('w', $offset) == 0) {
      $d = date($datefmt, strtotime("-1 week", $offset));
   } else {
      $w = "-" . (string)date('w', $offset);
      $d = date($datefmt, strtotime($w . " day", $offset));