php 如何显示一个月中的星期日?

7xllpg7q  于 2023-01-19  发布在  PHP
关注(0)|答案(5)|浏览(109)

我一直试图得到这个问题的答案,经过一些研究和开发,我也想出了解决方案

$begin = new DateTime('2014-11-01');
$end = new DateTime('2014-11-30');
$end = $end->modify('+1 day');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);

foreach ($daterange as $date) {
    $sunday = date('w', strtotime($date->format("Y-m-d")));
    if ($sunday == 0) {
        echo $date->format("Y-m-d") . "<br>";
    } else {
        echo'';
    }
}
sshcrbum

sshcrbum1#

请尝试以下方法:

$begin  = new DateTime('2014-11-01');
$end    = new DateTime('2014-11-30');
while ($begin <= $end) // Loop will work begin to the end date 
{
    if($begin->format("D") == "Sun") //Check that the day is Sunday here
    {
        echo $begin->format("Y-m-d") . "<br>";
    }

    $begin->modify('+1 day');
}
cvxl0en2

cvxl0en22#

这是显示本月所有星期日的另一种方法:

<?php
    function getSundays($y, $m)
{
    return new DatePeriod(
        new DateTime("first sunday of $y-$m"),
        DateInterval::createFromDateString('next sunday'),
        new DateTime("last day of $y-$m 23:59:59")
    );
}

foreach (getSundays(2014, 11) as $sunday) {
    echo $sunday->format("l, Y-m-d\n");
}
?>

参考此Codepad.viper

aemubtdh

aemubtdh3#

这是星期天的代码

function getSundays($y,$m){ 
    $date = "$y-$m-01";
    $first_day = date('N',strtotime($date));
    $first_day = 7 - $first_day + 1;
    $last_day =  date('t',strtotime($date));
    $days = array();
    for($i=$first_day; $i<=$last_day; $i=$i+7 ){
        //$days[] = $i;  //this will give days of sundays
        $days[] = "$y-$m-".$i;  //dates of sundays
    }
    return  $days;
}

$days = getSundays(2016,04);
print_r($days);
xwbd5t1u

xwbd5t1u4#

尝试使用此方法查找当前月份的星期日。

$month  = date('m');
$year  = date('Y');
$days = cal_days_in_month(CAL_GREGORIAN, $month,$year);
for($i = 1; $i<= $days; $i++){
   $day  = date('Y-m-'.$i);
   $result = date("l", strtotime($day));
   if($result == "Sunday"){
   echo date("Y-m-d", strtotime($day)). " ".$result."<br>";
   }
}
cwxwcias

cwxwcias5#

为了得到更快的结果,我们不需要循环31天,我们只需要第一个星期天的日期。

<?php
// change to "this month" for current month
$day  = new DateTime('first day of July 2022'); 
for ($i = 1; $i < 8; $i++)
{
    if ($day->format("D") == "Sun")
    { 
        // first sunday found, increment with 7
        while ($i <= 31)
        {
            echo $day->format("Y-m-d") . "\n";
            $i += 7;
            $day->modify("+7 day");
        }
        break;
    }

    $day->modify("+1 day");
}

相关问题