php函数获取日期范围内的所有星期一

发布于 2024-11-29 17:11:55 字数 243 浏览 1 评论 0原文

例子: $startDate 是 2007-02-05 星期一,$endDate 是 2007-02-20 星期二。然后我希望它列出:

Monday 2007-02-05
Monday 2007-02-12
Monday 2007-02-19

我查看了 PHP 手册,发现这个可以获取两个日期之间的所有天数。但如何按照我想要的方式去做呢? PHP代码:

Example:
$startDate is Monday 2007-02-05 and $endDate is Tuesday 2007-02-20. Then I want it to list:

Monday 2007-02-05
Monday 2007-02-12
Monday 2007-02-19

I looked at the PHP manual and found this to get all the days between two dates. But how to do it the way i want? PHP Code:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

缪败 2024-12-06 17:11:56

不要获取所有日期并循环遍历所有日期,而是获取开始日期后的第一个星期一,然后一次迭代 7 天:

$endDate = strtotime($endDate);
for($i = strtotime('Monday', strtotime($startDate)); $i <= $endDate; $i = strtotime('+1 week', $i))
    echo date('l Y-m-d', $i);

Rather than get all days and loop through them all, get the first Monday after the start date and then iterate 7 days at a time:

$endDate = strtotime($endDate);
for($i = strtotime('Monday', strtotime($startDate)); $i <= $endDate; $i = strtotime('+1 week', $i))
    echo date('l Y-m-d', $i);
爱你不解释 2024-12-06 17:11:56

我需要同样的东西并创建了一个简单的方法。

public function getMondaysInRange($dateFromString, $dateToString)
{
    $dateFrom = new \DateTime($dateFromString);
    $dateTo = new \DateTime($dateToString);
    $dates = [];

    if ($dateFrom > $dateTo) {
        return $dates;
    }

    if (1 != $dateFrom->format('N')) {
        $dateFrom->modify('next monday');
    }

    while ($dateFrom <= $dateTo) {
        $dates[] = $dateFrom->format('Y-m-d');
        $dateFrom->modify('+1 week');
    }

    return $dates;
}

然后使用它。

$dateFromString = '2007-02-05';
$dateToString = '2007-02-20';
var_dump($this->getMondaysInRange($dateFromString, $dateToString));

结果:

array (size=3)
  0 => string '2007-02-05' (length=10)
  1 => string '2007-02-12' (length=10)
  2 => string '2007-02-19' (length=10)

也许这对某人有帮助。

I needed the same and created a simple method.

public function getMondaysInRange($dateFromString, $dateToString)
{
    $dateFrom = new \DateTime($dateFromString);
    $dateTo = new \DateTime($dateToString);
    $dates = [];

    if ($dateFrom > $dateTo) {
        return $dates;
    }

    if (1 != $dateFrom->format('N')) {
        $dateFrom->modify('next monday');
    }

    while ($dateFrom <= $dateTo) {
        $dates[] = $dateFrom->format('Y-m-d');
        $dateFrom->modify('+1 week');
    }

    return $dates;
}

Then use it.

$dateFromString = '2007-02-05';
$dateToString = '2007-02-20';
var_dump($this->getMondaysInRange($dateFromString, $dateToString));

Result:

array (size=3)
  0 => string '2007-02-05' (length=10)
  1 => string '2007-02-12' (length=10)
  2 => string '2007-02-19' (length=10)

Maybe it will be helpful for somebody.

酒废 2024-12-06 17:11:56

您可以使用下面的函数来获取特定日期的日期范围之间的日期数组。

您必须在数字中输入开始日期、结束日期和天数。天数如下。
1 = 星期一,2 = 星期二,3 = 星期三,4 = 星期四。 5 = 星期五,6 = 星期六,7 = 星期日。

function getDateForSpecificDayBetweenDates($startDate,$endDate,$day_number){
$endDate = strtotime($endDate);
$days=array('1'=>'Monday','2' => 'Tuesday','3' => 'Wednesday','4'=>'Thursday','5' =>'Friday','6' => 'Saturday','7'=>'Sunday');
for($i = strtotime($days[$day_number], strtotime($startDate)); $i <= $endDate; $i = strtotime('+1 week', $i))
$date_array[]=date('Y-m-d',$i);

return $date_array;
 }

You can use below function to get a array of dates between a date range of specific day.

You have to input start date, end date and day number in number.The day number is as follow.
1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday. 5 = Friday, 6 = Saturday, 7 = Sunday.

function getDateForSpecificDayBetweenDates($startDate,$endDate,$day_number){
$endDate = strtotime($endDate);
$days=array('1'=>'Monday','2' => 'Tuesday','3' => 'Wednesday','4'=>'Thursday','5' =>'Friday','6' => 'Saturday','7'=>'Sunday');
for($i = strtotime($days[$day_number], strtotime($startDate)); $i <= $endDate; $i = strtotime('+1 week', $i))
$date_array[]=date('Y-m-d',$i);

return $date_array;
 }
如果没有你 2024-12-06 17:11:56
for ($i = strtotime($startDate); $i <= strtotime($endDate); $i = strtotime('+1 day', $i)) {
  if (date('N', $i) == 1) //Monday == 1
    echo date('l Y-m-d', $i); //prints the date only if it's a Monday
}
for ($i = strtotime($startDate); $i <= strtotime($endDate); $i = strtotime('+1 day', $i)) {
  if (date('N', $i) == 1) //Monday == 1
    echo date('l Y-m-d', $i); //prints the date only if it's a Monday
}
﹏雨一样淡蓝的深情 2024-12-06 17:11:56

我创建一个类,您将获得按日期名称排列的日期组范围内的所有日期:

 class DayHelper{

      const MONDAY = 'Mon';
      const TUESDAY = 'Tue';
      const WEDENSDAY = 'Wed';
      const THURSDAY = 'Thu';
      const FRIDAY = 'Fri';
      const SATURDAY = 'Sat';
      const SUNDAY = 'Sun';

   public function GetYeardays($dateStart, $dateend){
    $period = new \DatePeriod(
            new \DateTime($dateStart), new \DateInterval('P1D'), (new \DateTime($dateend))
    );
    $dates = iterator_to_array($period);

    $arrayreturn = array();
    foreach ($dates as $val) {
        $date = $val->format('Y-m-d'); //format date
        $get_name = date('l', strtotime($date)); //get week day
        $day_name = substr($get_name, 0, 3); // Trim day name to 3 chars
        switch ($day_name) {
            case self::MONDAY:
                $MONDAY[] = $date;
                $arrayreturn[self::MONDAY] = $MONDAY;
                break;
            case self::TUESDAY:
                $TUESDAY[] = $date;
                $arrayreturn[self::TUESDAY] = $TUESDAY;
                break;
            case self::WEDENSDAY:
                $WEDENSDAY[] = $date;
                $arrayreturn[self::WEDENSDAY] = $WEDENSDAY;
                break;
            case self::THURSDAY:
                $THURSDAY[] = $date;
                $arrayreturn[self::THURSDAY] = $THURSDAY;
                break;
            case self::FRIDAY:
                $FRIDAY[] = $date;
                $arrayreturn[self::FRIDAY] = $FRIDAY;
                break;
            case self::SATURDAY:
                $SATURDAY[] = $date;
                $arrayreturn[self::SATURDAY] = $SATURDAY;
                break;
            case self::SUNDAY:
                $SUNDAY[] = $date;
                $arrayreturn[self::SUNDAY] = $SUNDAY;
                break;
        }
    }
    return $arrayreturn;
  }
} 

输出将如下所示

 array (size=7)
 'Fri' => 
  array (size=5)
  0 => string '2016/01/01' (length=10)
  1 => string '2016/01/08' (length=10)
  2 => string '2016/01/15' (length=10)
  3 => string '2016/01/22' (length=10)
  4 => string '2016/01/29' (length=10)
 'Sat' => 
array (size=5)
  0 => string '2016/01/02' (length=10)
  1 => string '2016/01/09' (length=10)
  2 => string '2016/01/16' (length=10)
  3 => string '2016/01/23' (length=10)
  4 => string '2016/01/30' (length=10)
 'Sun' => 
array (size=4)
  0 => string '2016/01/03' (length=10)
  1 => string '2016/01/10' (length=10)
  2 => string '2016/01/17' (length=10)
  3 => string '2016/01/24' (length=10)
 'Mon' => 
array (size=4)
  0 => string '2016/01/04' (length=10)
  1 => string '2016/01/11' (length=10)
  2 => string '2016/01/18' (length=10)
  3 => string '2016/01/25' (length=10)
 'Tue' => 
array (size=4)
  0 => string '2016/01/05' (length=10)
  1 => string '2016/01/12' (length=10)
  2 => string '2016/01/19' (length=10)
  3 => string '2016/01/26' (length=10)
 'Wed' => 
array (size=4)
  0 => string '2016/01/06' (length=10)
  1 => string '2016/01/13' (length=10)
  2 => string '2016/01/20' (length=10)
  3 => string '2016/01/27' (length=10)
  'Thu' => 
array (size=4)
  0 => string '2016/01/07' (length=10)
  1 => string '2016/01/14' (length=10)
  2 => string '2016/01/21' (length=10)
  3 => string '2016/01/28' (length=10)

i Create A class, You get All Days In range Date Group By Name of Day:

 class DayHelper{

      const MONDAY = 'Mon';
      const TUESDAY = 'Tue';
      const WEDENSDAY = 'Wed';
      const THURSDAY = 'Thu';
      const FRIDAY = 'Fri';
      const SATURDAY = 'Sat';
      const SUNDAY = 'Sun';

   public function GetYeardays($dateStart, $dateend){
    $period = new \DatePeriod(
            new \DateTime($dateStart), new \DateInterval('P1D'), (new \DateTime($dateend))
    );
    $dates = iterator_to_array($period);

    $arrayreturn = array();
    foreach ($dates as $val) {
        $date = $val->format('Y-m-d'); //format date
        $get_name = date('l', strtotime($date)); //get week day
        $day_name = substr($get_name, 0, 3); // Trim day name to 3 chars
        switch ($day_name) {
            case self::MONDAY:
                $MONDAY[] = $date;
                $arrayreturn[self::MONDAY] = $MONDAY;
                break;
            case self::TUESDAY:
                $TUESDAY[] = $date;
                $arrayreturn[self::TUESDAY] = $TUESDAY;
                break;
            case self::WEDENSDAY:
                $WEDENSDAY[] = $date;
                $arrayreturn[self::WEDENSDAY] = $WEDENSDAY;
                break;
            case self::THURSDAY:
                $THURSDAY[] = $date;
                $arrayreturn[self::THURSDAY] = $THURSDAY;
                break;
            case self::FRIDAY:
                $FRIDAY[] = $date;
                $arrayreturn[self::FRIDAY] = $FRIDAY;
                break;
            case self::SATURDAY:
                $SATURDAY[] = $date;
                $arrayreturn[self::SATURDAY] = $SATURDAY;
                break;
            case self::SUNDAY:
                $SUNDAY[] = $date;
                $arrayreturn[self::SUNDAY] = $SUNDAY;
                break;
        }
    }
    return $arrayreturn;
  }
} 

The Output will be like this

 array (size=7)
 'Fri' => 
  array (size=5)
  0 => string '2016/01/01' (length=10)
  1 => string '2016/01/08' (length=10)
  2 => string '2016/01/15' (length=10)
  3 => string '2016/01/22' (length=10)
  4 => string '2016/01/29' (length=10)
 'Sat' => 
array (size=5)
  0 => string '2016/01/02' (length=10)
  1 => string '2016/01/09' (length=10)
  2 => string '2016/01/16' (length=10)
  3 => string '2016/01/23' (length=10)
  4 => string '2016/01/30' (length=10)
 'Sun' => 
array (size=4)
  0 => string '2016/01/03' (length=10)
  1 => string '2016/01/10' (length=10)
  2 => string '2016/01/17' (length=10)
  3 => string '2016/01/24' (length=10)
 'Mon' => 
array (size=4)
  0 => string '2016/01/04' (length=10)
  1 => string '2016/01/11' (length=10)
  2 => string '2016/01/18' (length=10)
  3 => string '2016/01/25' (length=10)
 'Tue' => 
array (size=4)
  0 => string '2016/01/05' (length=10)
  1 => string '2016/01/12' (length=10)
  2 => string '2016/01/19' (length=10)
  3 => string '2016/01/26' (length=10)
 'Wed' => 
array (size=4)
  0 => string '2016/01/06' (length=10)
  1 => string '2016/01/13' (length=10)
  2 => string '2016/01/20' (length=10)
  3 => string '2016/01/27' (length=10)
  'Thu' => 
array (size=4)
  0 => string '2016/01/07' (length=10)
  1 => string '2016/01/14' (length=10)
  2 => string '2016/01/21' (length=10)
  3 => string '2016/01/28' (length=10)
回忆追雨的时光 2024-12-06 17:11:56

我对响应进行了一些更改 https://stackoverflow.com/a/37300272/6871295

然后我可以获得之间的天数任意一天的日期和返回格式。

    public function getWeekDayInRange($weekday, $dateFromString, $dateToString, $format = 'Y-m-d')
    {
        $dateFrom = new \DateTime($dateFromString);
        $dateTo = new \DateTime($dateToString);
        $dates = [];

        if ($dateFrom > $dateTo) {
            return $dates;
        }

        if (date('N', strtotime($weekday)) != $dateFrom->format('N')) {
            $dateFrom->modify("next $weekday");
        }

        while ($dateFrom <= $dateTo) {
            $dates[] = $dateFrom->format($format);
            $dateFrom->modify('+1 week');
        }

        return $dates;
    }

I made some changes to response https://stackoverflow.com/a/37300272/6871295

Then I can get the days between dates for any day and return format.

    public function getWeekDayInRange($weekday, $dateFromString, $dateToString, $format = 'Y-m-d')
    {
        $dateFrom = new \DateTime($dateFromString);
        $dateTo = new \DateTime($dateToString);
        $dates = [];

        if ($dateFrom > $dateTo) {
            return $dates;
        }

        if (date('N', strtotime($weekday)) != $dateFrom->format('N')) {
            $dateFrom->modify("next $weekday");
        }

        while ($dateFrom <= $dateTo) {
            $dates[] = $dateFrom->format($format);
            $dateFrom->modify('+1 week');
        }

        return $dates;
    }
挽清梦 2024-12-06 17:11:56

这是用于获取“$startdate”的工作日并计算两个日期之间的工作日数的代码。

`$startdate` = '2015-03-01';
`$endate` = '2015-03-31';
`$recurringDay` = date('N', strtotime($startdate)); // recurring Day from date i.e monday = 1, Tuesday = 2 ...etc
$begin = new DateTime(`$startdate`);
    $end = new DateTime(date('Y-m-d',strtotime('+1 day', strtotime($endate))));
    while($begin format('Y-m-d');
        $day[] = $begin->format('N');
        $begin->modify('+1 day');
    }
   $c=0; // counter starts

   foreach($day as $key=>$dt) {

    if ($dt==`$recurringDay`) // compare it 
    {
      $k[] = $key;
      $c++;
    }
   }

   `$nofDays` = $c; // number of mondays , tuesday

   foreach($k as $pp) {
       //adding session code
       `$recurringDatetime[]` = $period[$pp]; // recurring dates
       }

       print_r(`$recurringDatetime`); // array of dates of monday, tuesday ..etc

This is code for fetching the weekday of "$startdate" and counting the number of weekdays between two dates.

`$startdate` = '2015-03-01';
`$endate` = '2015-03-31';
`$recurringDay` = date('N', strtotime($startdate)); // recurring Day from date i.e monday = 1, Tuesday = 2 ...etc
$begin = new DateTime(`$startdate`);
    $end = new DateTime(date('Y-m-d',strtotime('+1 day', strtotime($endate))));
    while($begin format('Y-m-d');
        $day[] = $begin->format('N');
        $begin->modify('+1 day');
    }
   $c=0; // counter starts

   foreach($day as $key=>$dt) {

    if ($dt==`$recurringDay`) // compare it 
    {
      $k[] = $key;
      $c++;
    }
   }

   `$nofDays` = $c; // number of mondays , tuesday

   foreach($k as $pp) {
       //adding session code
       `$recurringDatetime[]` = $period[$pp]; // recurring dates
       }

       print_r(`$recurringDatetime`); // array of dates of monday, tuesday ..etc
浅笑依然 2024-12-06 17:11:56
$dates = array();
$dates[] = strtotime($start);
for($i = 0; $i <= 12; $i++){
    $dates[] = strtotime('+1 week', $dates[$i]);
}
foreach($dates as $date){ echo date("d.m.Y", $date); }

我有类似的问题,课程可以在任何一天开始。该脚本选择开始日期并每周收集接下来的几天,直到达到所需的数量(在本例中为 12)。

$dates = array();
$dates[] = strtotime($start);
for($i = 0; $i <= 12; $i++){
    $dates[] = strtotime('+1 week', $dates[$i]);
}
foreach($dates as $date){ echo date("d.m.Y", $date); }

I had similar issue and courses can start on any day. This script picks starting day and collect next days every week until the wanted amount (12 in this case).

土豪我们做朋友吧 2024-12-06 17:11:56

将之前的 $startDate 和 $endDate 转换为时间戳:

foreach ($date = $startDate; $date <= $endDate; $date += 60 * 60 * 24) {
    if (strftime('%w', $date) == 1) {
        $mondays[] = strftime('%A %Y-%m-%d', $date);
    }
}

Convert $startDate and $endDate before that to timestamps:

foreach ($date = $startDate; $date <= $endDate; $date += 60 * 60 * 24) {
    if (strftime('%w', $date) == 1) {
        $mondays[] = strftime('%A %Y-%m-%d', $date);
    }
}
放手` 2024-12-06 17:11:56

只需添加为,

$date_from = "2007-02-05";
$date_from = strtotime($date_from);

$date_to="2007-02-20";
$date_to = strtotime($date_to);

for ($i=$date_from; $i<=$date_to; $i+=86400) {
$day = date("Y-m-d", $i);
$unixTimestamp = strtotime($day);

$dayOfWeek = date("l", $unixTimestamp);

if ($dayOfWeek == "Monday") {
    echo $day ."is a". $dayOfWeek;
}
}//end for

simply you can add as,

$date_from = "2007-02-05";
$date_from = strtotime($date_from);

$date_to="2007-02-20";
$date_to = strtotime($date_to);

for ($i=$date_from; $i<=$date_to; $i+=86400) {
$day = date("Y-m-d", $i);
$unixTimestamp = strtotime($day);

$dayOfWeek = date("l", $unixTimestamp);

if ($dayOfWeek == "Monday") {
    echo $day ."is a". $dayOfWeek;
}
}//end for
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文