Sunday was only 82,800 seconds long

Yesterday I learned the hard way that there are not always 86,400 seconds in a day. It just so happens that yesterday on Sunday there were only 82,800 because yesterday Sunday was only 23 hours long. This is particularly tricky when you use a programming language that stores time as seconds since Jan 1, 1970, and you want to iterate over a date range.

You might want to do something harmless like:

function date_range($start_date, $end_date) {
  
  $current_date = strtotime($start_date);
  $end_date     = strtotime($end_date);

  while ($current_date <= $end_date) {
    $date_range[] = strftime("%Y-%m-%d", $current_date);  
    $current_date += 86400;
  }

  return $date_range;
}

But don’t. If your date range falls over daylight saving time (as mine did yesterday), you’ll be missing your end date. I fixed this particular bug by relying on the liberal input of strtotime:

function date_range($start_date, $end_date) {
  
  $current_date = strtotime($start_date);
  $end_date     = strtotime($end_date);

  while ($current_date <= $end_date) {
    $date_range[] = strftime("%Y-%m-%d", $current_date);
    $current_date = strtotime("+1 day", $current_date);
  }

  return $date_range;
}

So, word to the wise: wcgrep 86400

Update: Stephanie looked at my post and said, “Didn’t daylight saving time start on Sunday?” Umm, yes, yes it did.

Care to Comment?

Or if you'd prefer to get in touch privately, please send me an email.

Name

Email (optional)

Blog (optional)