获取两个日期之间每周的每一天的数量

时间:2013-03-13 21:25:18

标签: php date

我需要获得两个日期之间一周中每一天的天数,例如:

2013-01-01 to 2013-01-15

Mo:2
Tu:3
We:2
Th:2
Fr:2
Sa:2
Su:2

我有这个代码不知道我以前在哪里得到它但似乎工作但是意识到有些日期范围不起作用,如2013-03-01至2013-03-11它周一报告为1天2天。

function daysOfWeekBetween($start_date, $end_date, $weekDay)
{
   $first_date = strtotime($start_date." -1 days");
   $first_date = strtotime(date("M d Y",$first_date)." next ".$weekDay);

   $last_date = strtotime($end_date." +1 days");
   $last_date = strtotime(date("M d Y",$last_date)." last ".$weekDay);

   return  floor(($last_date - $first_date)/(7*86400)) + 1;
}

daysOfWeekBetween($date_range['start_date'], $date_range['end_date'], 'Monday');

2 个答案:

答案 0 :(得分:0)

查看mktime()手册。第一个例子完全符合你的需要。

试试这个:

date_default_timezone_set('UTC');

function count_weekdays_between($start, $end) {
    if (preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d)$/', $start, $start) && preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d)$/', $end, $end)) {
        $start  = mktime(0, 0, 0, $start[2], $start[3], $start[1]);
        $end    = mktime(0, 0, 0,   $end[2],   $end[3],   $end[1]);
        $offset = date('w', $start);
        $delta  = ($end - $start) / 86400;

        $result = array_fill(0, 7, floor($delta / 7));

        for ($i = 0; $i <= ($delta % 7); ++$i) {
            $result[$offset]++;
            $offset = ($offset + 1) % 7;
        }
        return $result;
    }
    return false;
}

答案 1 :(得分:0)

想出一个解决方案:

    $interval = DateInterval::createFromDateString('1 day');
    $begin = new DateTime($date_range['start_date']);
    $end = new DateTime($date_range['end_date']);
    $period = new DatePeriod($begin, $interval, $end);
    foreach($period as $dt)
    {
        $inner_data['average_days_counter'][$dt->format('D')] = isset($inner_data['average_days_counter'][$dt->format('D')]) ? $inner_data['average_days_counter'][$dt->format('D')] + 1 : 1;
    }
    // Array ( [Mon] => 2 [Tue] => 1 [Wed] => 1 [Thu] => 1 [Fri] => 2 [Sat] => 2 [Sun] => 2 )