找一个月的周期(从星期一开始)

时间:2012-09-07 12:15:31

标签: php time duration period week-number

我正在尝试查找给定月份和年份的每周时段。日期应从星期一开始,到星期日结束。如果该月的第一天是星期日(2011年5月),它应该是第一个元素。

2011年5月

  • 5月1日(星期日)
  • 5月2日 - 5月8日(周一至周日)
  • 5月9日 - 5月15日(周一至周日)
  • 5月17日 - Ma6y 22(周一至周日)
  • 5月23日 - 5月29日(周一至周日)
  • 5月30日 - 5月31日(周一至周二)

2012年9月

  • 9月1日 - 9月2日
  • 9月3日 - 9月9日
  • 9月10日 - 9月16日
  • 9月17日 - 9月23日
  • 9月24日 - 9月30日

我正在使用此函数计算两个日期的周数 - 即。这个月的第一天和一个月的最后一天。

public function getWeekNumbers($startDate, $endDate)
{
    $p = new DatePeriod(
            new DateTime($startDate),
            new DateInterval('P1W'),
            new DateTime($endDate)
    );

    $weekNumberList = array();

    foreach ($p as $w)
    {
        $weekNumber = $w->format('W');
        $weekNumberList[] = ltrim($weekNumber, '0');
    }

    return $weekNumberList;
}

奇怪的是,对于1月份,当我期待[1,2,3,4,5]时,它会返回[52,1,2,3,4]的周数。

一旦我有周数,我就像这样使用它们:

//The following loop will populate the dataset with the entire month's durations - regardless if hours were worked or not.
    $firstDayOfMonth = date('Y-m-d', strtotime("first day of {$this->year}-{$monthName}"));
    $lastDayOfMonth = date('Y-m-d', strtotime("last day of {$this->year}-{$monthName}"));

    foreach ($this->getWeekNumbers($firstDayOfMonth, $lastDayOfMonth) as $key => $weekId)
    {
        // find first mоnday of the year
        $firstMon = strtotime("mon jan {$this->year}");

        // calculate how many weeks to add
        $weeksOffset = $weekId - date('W', $firstMon);

        $beginDays = $weeksOffset * 7;
        $endDays = ($weeksOffset * 7) + 6;

        $searchedMon = strtotime(date('Y-m-d', $firstMon) . " +{$beginDays} days");
        $searchedSun = strtotime(date('Y-m-d', $firstMon) . " +{$endDays} days");

        echo date("M d", $searchedMon) . " - " . date("M d", $searchedSun);
    }

因为getWeekNumbers函数没有返回我期望的周数,所以上述函数的输出是

并不奇怪
  • 12月24日 - 12月30日(2012)
  • 1月2日 - 1月8日(2012)
  • 1月9日 - 1月15日(2012)
  • 1月16日 - 1月22日(2012)
  • 1月23日 - 1月29日(2012)

请注意,第1行(12月24日 - 12月30日)是当年(2012年)的结束,而不是去年年底(2011年)。

理想情况下,我希望它看起来像enter image description here

有什么想法吗?谢谢!

3 个答案:

答案 0 :(得分:3)

如果您需要选定月份的所有周数以及所选周的所有日期,那么这就是您所需要的:

function getWeekDays($month, $year)
{
    $p = new DatePeriod(
        DateTime::createFromFormat('!Y-n-d', "$year-$month-01"),
        new DateInterval('P1D'),
        DateTime::createFromFormat('!Y-n-d', "$year-$month-01")->add(new DateInterval('P1M'))
    );

    $datesByWeek = array();
    foreach ($p as $d) {
        $dateByWeek[ $d->format('W') ][] = $d;
    }
    return $dateByWeek;
}

getWeekDays()函数返回多维数组。第一个关键是周数。 2级是数组,其日期保存为DateTime对象。

获取示例:

print_r( getWeekDays(5, 2011) ); # May 2011
print_r( getWeekDays(9, 2012) ); # Sep 2012

我有一点额外的时间,所以我写了一个例子; - )

$datesByWeek = getWeekDays(8, 2012);
$o = '<table border="1">';
$o.= '<tr><th>Week</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th></tr>';
foreach ($datesByWeek as $week => $dates) {
    $firstD = $dates[0];
    $lastD = $dates[count($dates)-1];

    $o.= "<tr>";
    $o.= "<td>" . $firstD->format('M d') . ' - ' . $lastD->format('M d') . "</td>";
    $N = $firstD->format('N');
    for ($i = 1; $i < $N; $i++) {
        $o.= "<td>-</td>";
    }
    foreach ($dates as $d) {
        $o.= "<td>" . $d->format('d.') . " / 0.00</td>";
            # for selected date do you magic
    }
    $N = $lastD->format('N');
    for ($i = $N; $i < 7; $i++) {
        $o.= "<td>-</td>";
    }
    $o.= "</tr>";
}
$o.= '</table>';
echo $o;

输出如下: enter image description here

答案 1 :(得分:2)

这完美! phpfiddle here

<?php
// start and end must be timestamps !!!!
$start = 1346976000;  //  Thu 2012-09-06
$end   = 1348704000;  //  Tue 2012-09-26

// generate the weeks 
$weeks = generateweeks($start, $end);

// diaplay the weeks
echo 'From: '.fDate($start).'<br>';
foreach ($weeks as $week){
   echo fDate($week['start']).' '.fDate($week['end']).'<br>';
}
echo 'To: '.fDate($end).'<br>';

/*   outputs this:
From: Thu 2012-09-06
Thu 2012-09-06 Sun 2012-09-09
Mon 2012-09-10 Sun 2012-09-16
Mon 2012-09-17 Sun 2012-09-23
Mon 2012-09-24 Wed 2012-09-26
To: Wed 2012-09-26
*/


// $start and $end must be unix timestamps (any range)
//  returns an array of arrays with 'start' and 'end' elements set 
//  for each week (or part of week) for the given interval
//  return values are also in timestamps
function generateweeks($start,$end){
    $ret = array();
    $start = E2D($start);
    $end = E2D($end);

    $ns = nextSunday($start);

    while(true){
        if($ns>=$end) {insert($ret,$start,$end);return $ret;}
        insert($ret,$start,$ns);
        $start = $ns +1;
        $ns+=7;
    }
}



// helper function to append the array and convert back to unix timestamp
function insert(&$arr, $start, $end){$arr[] = array('start'=>D2E($start), 'end'=>D2E($end));}
// recives any date on CD format returns next Sunday on CD format
function nextSunday($Cdate){return $Cdate + 6  - $Cdate % 7;}
// recives any date on CD format returns previous Monday on CD format // finaly not used here
function prevMonday($Cdate){return $Cdate      - $Cdate % 7;}   
// recives timestamp returns CD
function E2D($what){return floor($what/86400)+2;}     // floor may be optional in some circunstances
// recives CD returns timestamp
function D2E($what){return ($what-2)*86400;}          // 24*60*60
// just format the timestamp for output, you can adapt it to your needs
function fDate($what){return date('D Y-m-d',$what);}

答案 2 :(得分:1)

以下假设用户可以选择他们想要运行报告的月份和年份(月份为1-12,年份为YYYY)。可能有一种更优雅的方式,但这似乎对我有用。此外,在帖子的顶部,您说您希望周数为周一至周日。但是,您在底部的示例/屏幕截​​图显示周是星期六到星期六。以下是周一至周日的原定目标。

$month = $_POST["month"];
$year = $_POST["year"];

$endDate = date("t", strtotime($year."-".$month."-01"));

$dayOfWeekOfFirstOfMonth = date("w", strtotime($year."-".$month."-01"));
$lastDayOfFirstWeek = 8 - $dayOfWeekOfFirstOfMonth;

$weeksArray = array(array("firstDay"=>1, "lastDay"=>$lastDayOfFirstWeek));

$loopDate = $lastDayOfFirstWeek + 1;

while($loopDate < $endDate)
{
    $weeksArray[] = array("firstDay"=>$loopDate, "lastDay"=>($loopDate+6 > $endDate ? $endDate : $loopDate+6));
    $loopDate+=7;
}

foreach($weeksArray as $week)
{
    echo date("M d", strtotime($year."-".$month."-".$week["firstDay"])) . " - " . date("M d", strtotime($year."-".$month."-".$week["lastDay"])) . "\n";
}