1

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

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');
4

2 回答 2

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;
}
于 2013-03-13T21:28:55.747 回答
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 ) 
于 2013-03-13T23:08:19.163 回答