php - How to display sundays in a month?
Get the solution ↓↓↓I have been trying to get the answer for this question and after some R&D i have come up with the solution too
$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'';
}
}
Answer
Solution:
Try this way:
$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');
}
Answer
Solution:
Here is the code for sundays
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);
Answer
Solution:
This is another method for shown all sundays in current month:
<?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");
}
?>
Refer this Codepad.viper
Answer
Solution:
Try this one to find Sundays of the current month.
$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>";
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.