1

我正在尝试查找给定月份和年份的每周周期。日期应从星期一开始,到星期日结束。如果一个月的 1 日是星期日(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)

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

理想情况下,我希望它看起来像在此处输入图像描述

有任何想法吗?谢谢!!

4

3 回答 3

5

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

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;

输出如下所示: 在此处输入图像描述

于 2012-09-07T19:48:06.037 回答
2

以下假设用户可以选择他们想要运行报告的月份和年份(发布的值是月份的 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";
}
于 2012-09-07T17:27:36.540 回答
2

这完美!phpfiddle在这里

<?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);}
于 2012-09-07T16:28:02.043 回答