如何在一个月内显示星期日?

时间:2014-11-19 09:40:42

标签: php date

我一直试图得到这个问题的答案,并且在一些R& D之后我也想出了解决方案

$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'';
    }
}

4 个答案:

答案 0 :(得分:4)

尝试这种方式:

$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');
}

答案 1 :(得分:1)

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

<?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

答案 2 :(得分:0)

以下是星期日的代码

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;
    }
    return  $days;
}

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

答案 3 :(得分:0)

  

尝试使用此功能查找当月的星期日。

$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>";
   }
}