开发者

php 8 days created for week

I have the following code that creates a list of dates between a range. If I supply a day of the week it will get all dates for thoes dates in the range. If I dont it will get all days.

My problem is that from the 24th of october to the 29th it returns an extra day. I noticed the before when I added the extra code to get the dates of a day of the week.

The problem line I think is array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry

function createDateRangeArray($strDateFrom,$strDateTo,$dateOfWeek=null) {
  // takes two dates formatted as YYYY-MM-DD and creates an
  // inclusive array of the dates between the from and to dates.

  // could test validity of dates here but I'm already doing
  // that in the main script

  $aryRange=array();

  $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),substr($strDateFrom,8,2),substr($strDateFrom,0,4));
  $iDateTo=mktime(1,0,0,substr($strDateTo,5,2),substr($strDateTo,8,2),substr($strDateTo,0,4));

  if ($iDateTo>=$iDateFrom) {

    if(!isset($dateOfWeek)) {   
        array_push($aryRange,date('Y-m-d',$iDateFrom)); // fi开发者_开发知识库rst entry

        while ($iDateFrom<$iDateTo) {
          $iDateFrom+=86400; // add 24 hours
          array_push($aryRange,date('Y-m-d',$iDateFrom));
        }
    } else {

        while ($iDateFrom<$iDateTo) {
          if(date('w',$iDateFrom)==$dateOfWeek)
              array_push($aryRange,date('Y-m-d',$iDateFrom));
              $iDateFrom+=86400; // add 24 hours
        }       
    }
  }

  if(count($aryRange)<1){
    return false;
  } else{
    return $aryRange;
  }

}


Wouldn't it be simpler to use the strtotime() function? http://php.net/manual/en/function.strtotime.php

$iDateFrom = strtotime("+1 day", $iDateFrom); // add 1 day


You have to account for the daylight saving time.

-> http://en.wikipedia.org/wiki/Daylight_saving_time


You're adding 24 hours each time. That's not quite the same thing as adding a day. I strongly suspect that you're operating in a time zone where the clock goes back on October 23rd or October 30th, and this is messing up your calculations.

It's not entirely clear to me what the best solution is for you here, but hopefully explaining what is going on will be a good start...


The quick & dirty solution is to add a couple of hours of time difference to the dates you're comparing. This way daylight saving time doesn't affect the calculations enough to throw them off.

$iDateFrom=mktime(12,0,0,substr($strDateFrom,5,2),substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2),substr($strDateTo,8,2),substr($strDateTo,0,4));

The better solution is to use actual date manipulating functions instead of manually adding 24 hours.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜