Count number of Sunday's in given Month and year - php

I want output to be count of sunday's present in given month and year.
This is my code:
$months=$_POST['month'];
$years=$_POST['year'];
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>';
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>';
$num_sundays='';
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++)
{
if(date('l',strtotime($fromdt) + ($i * 86400)) == 'Sunday')
{
$num_sundays++;
}
}
I am not getting any output if i echo $num_sundays. Please help me . I am new to PHP

You just need to remove <br> from these two lines:
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>';
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>';
Otherwise this will be the part of start and end date, and your strtotime() will return false.
Example:
<?php
$months = 12;
$years=2016;
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>';
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>';
var_dump(strtotime($todt));
var_dump(strtotime($fromdt));
?>
DEMO: This will return false for both.
Example 2:
<?php
$months = 12;
$years=2016;
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) ;
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years"));
var_dump(strtotime($todt));
var_dump(strtotime($fromdt));
?>
DEMO: This will return the values
Complete Example:
<?php
$months = 12;
$years=2016;
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) ;
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years"));
$num_sundays='';
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++)
{
if(date('l',strtotime($fromdt) + ($i * 86400)) == 'Sunday')
{
$num_sundays++;
}
}
echo "Total Count is: ".$num_sundays;
?>
DEMO: This will return 4 sunday

Without loop. I hope this gives the correct results.
date_default_timezone_set('UTC');
// unix timestamp 0 = Thursday, 01-Jan-70 00:00:00 UTC
// unix timestamp 259200 = Sunday, 04-Jan-70 00:00:00 UTC
$sun_first = strtotime('1970-01-04');
$t1 = strtotime('2018-10-01') - $sun_first - 86400;
$t2 = strtotime('2018-10-31') - $sun_first;
$sun_count = floor($t2 / 604800) - floor($t1 / 604800); // total Sunday from 2018-10-01 to 2018-10-31
echo $sun_count; // 4

Get all sunday in month see below code:
function total_sun($month,$year)
{
$sundays=0;
$total_days=cal_days_in_month(CAL_GREGORIAN, $month, $year);
for($i=1;$i<=$total_days;$i++)
if(date('N',strtotime($year.'-'.$month.'-'.$i))==7)
$sundays++;
return $sundays;
}
echo total_sun(11,2016);
http://phpio.net/s/l9f

Check following Example. I work perfectly..
function dayCount($day,$month,$year){
$totalDay=cal_days_in_month(CAL_GREGORIAN,$month,$year);
$count=0;
for($i=1;$totalDay>=$i;$i++){
if( date('l', strtotime($year.'-'.$month.'-'.$i))==ucwords($day)){
$count++;
}
}
echo $count;
}
dayCount('saturday',3,2019);

working example dorcode calculation
$startd="31-7-2006 15:30:00";
$endd="31-7-2007 15:30:00";
$startDate=$startd;
$endDate=$endd;
$startDate1 = strtotime($startDate);
$endDate1 = strtotime($endDate);
if($startDate1>$endDate1)
{
$startDate1 = strtotime($endDate);
$endDate1 = strtotime($startDate);
} else {
$startDate1 = strtotime($startDate);
$endDate1 = strtotime($endDate);
}
$p=0;
for($i = strtotime("Sunday", $startDate1); $i <= $endDate1;
$i =strtotime('+1 week', $i))
{
$p++;
echo $p.": ".date('F d, Y', $i)."<br>";
}

To get a count of any given day in a given month in a year:
$year = '2019';
$month = '2';
$day = 'Tuesday';
$count = 0;
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$date = new Datetime($year.'-'.$month.'-01');
for($i=1; $i<$days; $i++){
if($date->format('l') == $day){
$count++;
}
$date->modify('+1 day');
}
echo "Count: $count";

Use this code if it helps you
public function countWeekendDays($month, $year){
$daytime = strtotime(date($year."/".$month."/01 00:00:01"));
$daysOfMonth = date("t", $daytime);
$weekdays = 0;
for ($day=1; $day <= $daysOfMonth; $day++) {
$time = strtotime(date($year.'/'.$month.'/'.$day.' 00:00:01'));
$dayStr = date('l', $time);
if ($dayStr == 'Saturday' || $dayStr == 'Sunday') {
$weekdays++;
}
}
return $weekdays;
}

Simple code for day count:
function dayCount($day,$month,$year){
$totaldays = date('t',strtotime($year.'-'.$month.'-01'));
$countday = 4;
if(($totaldays - $day) >= 28 ){
$countday = 5;
}
return $countday;
}
echo dayCount(1,9,2019);

$day =Carbon\Carbon::now("Asia/Kolkata")->daysInMonth;
echo $day.'</br>';
if($day = 28) {
$weekend = 8;
}elseif($day = 29) {
$first_day_saturday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSaturday();
$first_day_sunday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSunday();
if($first_day_saturday || $first_day_sunday) {
$weekend = 9;
}else {
$weekend = 8;
}
}elseif($day = 30) {
$first_day_saturday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSaturday();
$first_day_sunday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSunday();
if ($first_day_saturday) {
$weekend = 10;
}elseif ($first_day_sunday) {
$weekend = 9;
}else {
$weekend = 8;
}
}else {
$first_day_thrusday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isThursday();
$first_day_friday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isFriday();
$first_day_saturday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSaturday();
$first_day_sunday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSunday();
if ($first_day_friday || $first_day_saturday) {
$weekend = 10;
}elseif ($first_day_sunday || $first_day_thrusday) {
$weekend = 9;
}else {
$weekend = 8;
}
}
echo $weekend.'</br>';

Related

how to display months in descending order starting with current month in php [duplicate]

I'm trying to list all months between two dates.
For example; start date is: 2010-12-02 and last date is: 2012-05-06
I want to list something like this:
2010-12
2011-01
2011-02
2011-03
2011-04
.
.
.
2012-04
2012-05
This is what I have tried and it is not working at all:
$year_min = 2010;
$year_max = 2012;
$month_min = 12;
$month_max = 5;
for($y=$year_min; $y<=$year_max; $y++)
{
for($m=$month_min; $m<=$month_max; $m++)
{
$period[] = $y.$m;
}
}
PHP 5.3
$start = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
See it in action
PHP 5.4 or newer
$start = (new DateTime('2010-12-02'))->modify('first day of this month');
$end = (new DateTime('2012-05-06'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
The part where we modify the start and end dates to the first of the month is important. If we didn't, and the current day higher then the last day in February (i.e. 28 in non-leap years, 29 in leap years) this would skip February.
function getMonthsInRange($startDate, $endDate)
{
$months = array();
while (strtotime($startDate) <= strtotime($endDate)) {
$months[] = array(
'year' => date('Y', strtotime($startDate)),
'month' => date('m', strtotime($startDate)),
);
// Set date to 1 so that new month is returned as the month changes.
$startDate = date('01 M Y', strtotime($startDate . '+ 1 month'));
}
return $months;
}
You must make a difference between two months of the same year and two months of different years.
$year_min = substr($row['contractStart'], 0, 4);
$year_max = substr($row['contractEnd'], 0, 4);
$month_min = substr($row['contractStart'], 5, 2);
$month_min = substr($row['contractEnd'], 5, 2);
$period = array();
try {
if ($year_min > $year_max)
throw new Exception();
else if ($year_min == $year_max)
if ($month_min > $month_max)
throw new Exception();
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
else {
for ($month = $month_min; $month <= 12; $month++) {
$period[] = $month . '-' . $year_min;
}
for ($year = $year_min + 1; $year < $year_max; $year++) {
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
}
for ($month = 1; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year_max;
}
}
implode("<br />\r\n", $period);
}
catch (Exception $e) {
echo 'Start date occurs after end date.'
}
That's for the hard way. Now there is a quick and easy way that is already given as an answer which I recommend you to choose.
This was my solution since DateTime is not available in my server environment.
$a = "2007-01-01";
$b = "2008-02-15";
$i = date("Ym", strtotime($a));
while($i <= date("Ym", strtotime($b))){
echo $i."\n";
if(substr($i, 4, 2) == "12")
$i = (date("Y", strtotime($i."01")) + 1)."01";
else
$i++;
}
Try it out: http://3v4l.org/BZOmb
In Laravel,
$period = \Carbon\CarbonPeriod::create('2017-06-28', '1 month', '2019-06-01');
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
October 2021 Update
If you have dates selected by the user, here's a solution
$from = date('Y-m-d', strtotime($_POST['from']));
$to = date('Y-m-d', strtotime($_POST['to']));
$counter = 1;
$max_date = strtotime($to);
$current_date = strtotime($from);
$dates = [];
$months = [];
$loop = true;
while($loop) {
if(strtotime(date('Y-m-d',$current_date)." +".$counter."days") >= $max_date) $loop = false;
else {
$current_date = strtotime(date('Y-m-d', $current_date)." +".$counter."days");
$date = date('Y-m-d', $current_date);
$dates[] = $date;
$months[] = date('Y-m', $current_date);
$counter++;
}
}
$months = array_unique($months);
echo '<pre>';
print_r($dates);
echo '<br>';
print_r($months);
echo '</pre>';

Get the same specific date on each month of the whole year

I am working on a "cut-off" date and I need to set it on every month. Say, I set the cut-off date to August 25 for this year, then it should be September 25, October 25 and so on till the year ends.
Here's the code I have:
$now = "2015-08-25";
$nextDate = getCutoffDate($now);
echo $nextDate;
function getCutoffDate($start_date)
{
$date_array = explode("-",$start_date); // split the array
// var_dump($date_array);
$year = $date_array[0];
$month = $date_array[1];
$day = $date_array[2];
/*if (date('n', $now)==12)
{
return date("Y-m-d",strtotime(date("Y-m-d", $start_date) . "+1 month"));
}*/
if (date("d") <= $day) {
$billMonth = date_format(date_create(), 'm');
}
else{
$billMonth = date_format(date_modify(date_create(), 'first day of next month'), 'm');
}
// echo date("d").' '. $billMonth.'<br>';
$billMonthDays = cal_days_in_month(CAL_GREGORIAN, ($billMonth), date("Y"));
// echo $billMonthDays.'<br>';
if ($billMonthDays > $day) {
$billDay = $day;
} else {
$billDay = $billMonthDays;
}
}
I got this from here: http://www.midwesternmac.com/blogs/jeff-geerling/php-calculating-monthly
It returns the same date for the next month only, but how do I get the specific date of EACH month of the current year? Kindly leave your thoughts. Still a newbie here, sorry.
In that case, this should be enough:
<?php
for($i=8; $i<=12; $i++) {
echo sprintf('25-%02d-2015', $i) . '<br>';
}
but if you need more flexible way:
<?php
$date = new DateTime('25-08-2015');
function getCutoffDate($date) {
$days = cal_days_in_month(CAL_GREGORIAN, $date->format('n'), $date->format('Y'));
$date->add(new DateInterval('P' . $days .'D'));
return $date;
}
for($i = 0; $i < 5; $i++) {
$date = getCutoffDate($date);
echo $date->format('d-m-Y') . '<br>';
}
This should print:
25-09-2015
25-10-2015
25-11-2015
25-12-2015
25-01-2016

Loop for numbering weeks of the year [duplicate]

I'm trying to list all months between two dates.
For example; start date is: 2010-12-02 and last date is: 2012-05-06
I want to list something like this:
2010-12
2011-01
2011-02
2011-03
2011-04
.
.
.
2012-04
2012-05
This is what I have tried and it is not working at all:
$year_min = 2010;
$year_max = 2012;
$month_min = 12;
$month_max = 5;
for($y=$year_min; $y<=$year_max; $y++)
{
for($m=$month_min; $m<=$month_max; $m++)
{
$period[] = $y.$m;
}
}
PHP 5.3
$start = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
See it in action
PHP 5.4 or newer
$start = (new DateTime('2010-12-02'))->modify('first day of this month');
$end = (new DateTime('2012-05-06'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
The part where we modify the start and end dates to the first of the month is important. If we didn't, and the current day higher then the last day in February (i.e. 28 in non-leap years, 29 in leap years) this would skip February.
function getMonthsInRange($startDate, $endDate)
{
$months = array();
while (strtotime($startDate) <= strtotime($endDate)) {
$months[] = array(
'year' => date('Y', strtotime($startDate)),
'month' => date('m', strtotime($startDate)),
);
// Set date to 1 so that new month is returned as the month changes.
$startDate = date('01 M Y', strtotime($startDate . '+ 1 month'));
}
return $months;
}
You must make a difference between two months of the same year and two months of different years.
$year_min = substr($row['contractStart'], 0, 4);
$year_max = substr($row['contractEnd'], 0, 4);
$month_min = substr($row['contractStart'], 5, 2);
$month_min = substr($row['contractEnd'], 5, 2);
$period = array();
try {
if ($year_min > $year_max)
throw new Exception();
else if ($year_min == $year_max)
if ($month_min > $month_max)
throw new Exception();
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
else {
for ($month = $month_min; $month <= 12; $month++) {
$period[] = $month . '-' . $year_min;
}
for ($year = $year_min + 1; $year < $year_max; $year++) {
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
}
for ($month = 1; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year_max;
}
}
implode("<br />\r\n", $period);
}
catch (Exception $e) {
echo 'Start date occurs after end date.'
}
That's for the hard way. Now there is a quick and easy way that is already given as an answer which I recommend you to choose.
This was my solution since DateTime is not available in my server environment.
$a = "2007-01-01";
$b = "2008-02-15";
$i = date("Ym", strtotime($a));
while($i <= date("Ym", strtotime($b))){
echo $i."\n";
if(substr($i, 4, 2) == "12")
$i = (date("Y", strtotime($i."01")) + 1)."01";
else
$i++;
}
Try it out: http://3v4l.org/BZOmb
In Laravel,
$period = \Carbon\CarbonPeriod::create('2017-06-28', '1 month', '2019-06-01');
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
October 2021 Update
If you have dates selected by the user, here's a solution
$from = date('Y-m-d', strtotime($_POST['from']));
$to = date('Y-m-d', strtotime($_POST['to']));
$counter = 1;
$max_date = strtotime($to);
$current_date = strtotime($from);
$dates = [];
$months = [];
$loop = true;
while($loop) {
if(strtotime(date('Y-m-d',$current_date)." +".$counter."days") >= $max_date) $loop = false;
else {
$current_date = strtotime(date('Y-m-d', $current_date)." +".$counter."days");
$date = date('Y-m-d', $current_date);
$dates[] = $date;
$months[] = date('Y-m', $current_date);
$counter++;
}
}
$months = array_unique($months);
echo '<pre>';
print_r($dates);
echo '<br>';
print_r($months);
echo '</pre>';

How to list all months between two dates

I'm trying to list all months between two dates.
For example; start date is: 2010-12-02 and last date is: 2012-05-06
I want to list something like this:
2010-12
2011-01
2011-02
2011-03
2011-04
.
.
.
2012-04
2012-05
This is what I have tried and it is not working at all:
$year_min = 2010;
$year_max = 2012;
$month_min = 12;
$month_max = 5;
for($y=$year_min; $y<=$year_max; $y++)
{
for($m=$month_min; $m<=$month_max; $m++)
{
$period[] = $y.$m;
}
}
PHP 5.3
$start = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
See it in action
PHP 5.4 or newer
$start = (new DateTime('2010-12-02'))->modify('first day of this month');
$end = (new DateTime('2012-05-06'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
The part where we modify the start and end dates to the first of the month is important. If we didn't, and the current day higher then the last day in February (i.e. 28 in non-leap years, 29 in leap years) this would skip February.
function getMonthsInRange($startDate, $endDate)
{
$months = array();
while (strtotime($startDate) <= strtotime($endDate)) {
$months[] = array(
'year' => date('Y', strtotime($startDate)),
'month' => date('m', strtotime($startDate)),
);
// Set date to 1 so that new month is returned as the month changes.
$startDate = date('01 M Y', strtotime($startDate . '+ 1 month'));
}
return $months;
}
You must make a difference between two months of the same year and two months of different years.
$year_min = substr($row['contractStart'], 0, 4);
$year_max = substr($row['contractEnd'], 0, 4);
$month_min = substr($row['contractStart'], 5, 2);
$month_min = substr($row['contractEnd'], 5, 2);
$period = array();
try {
if ($year_min > $year_max)
throw new Exception();
else if ($year_min == $year_max)
if ($month_min > $month_max)
throw new Exception();
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
else {
for ($month = $month_min; $month <= 12; $month++) {
$period[] = $month . '-' . $year_min;
}
for ($year = $year_min + 1; $year < $year_max; $year++) {
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
}
for ($month = 1; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year_max;
}
}
implode("<br />\r\n", $period);
}
catch (Exception $e) {
echo 'Start date occurs after end date.'
}
That's for the hard way. Now there is a quick and easy way that is already given as an answer which I recommend you to choose.
This was my solution since DateTime is not available in my server environment.
$a = "2007-01-01";
$b = "2008-02-15";
$i = date("Ym", strtotime($a));
while($i <= date("Ym", strtotime($b))){
echo $i."\n";
if(substr($i, 4, 2) == "12")
$i = (date("Y", strtotime($i."01")) + 1)."01";
else
$i++;
}
Try it out: http://3v4l.org/BZOmb
In Laravel,
$period = \Carbon\CarbonPeriod::create('2017-06-28', '1 month', '2019-06-01');
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
October 2021 Update
If you have dates selected by the user, here's a solution
$from = date('Y-m-d', strtotime($_POST['from']));
$to = date('Y-m-d', strtotime($_POST['to']));
$counter = 1;
$max_date = strtotime($to);
$current_date = strtotime($from);
$dates = [];
$months = [];
$loop = true;
while($loop) {
if(strtotime(date('Y-m-d',$current_date)." +".$counter."days") >= $max_date) $loop = false;
else {
$current_date = strtotime(date('Y-m-d', $current_date)." +".$counter."days");
$date = date('Y-m-d', $current_date);
$dates[] = $date;
$months[] = date('Y-m', $current_date);
$counter++;
}
}
$months = array_unique($months);
echo '<pre>';
print_r($dates);
echo '<br>';
print_r($months);
echo '</pre>';

how to get date format ( week 3 of month Jan) from week no

I have array of week numbers from 1 to 52. how i can convert it to
[week 1 jan],[week 2 jan] .......
using PHP
OK ... I fix it and here is my code
function getWeeks($date, $rollover)
{
$cut = substr($date, 0, 8);
$daylen = 86400;
$timestamp = strtotime($date);
$first = strtotime($cut . "00");
$elapsed = ($timestamp - $first) / $daylen;
$i = 1;
$weeks = 1;
for($i; $i<=$elapsed; $i++)
{
$dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
$daytimestamp = strtotime($dayfind);
$day = strtolower(date("l", $daytimestamp));
if($day == strtolower($rollover)) $weeks ++;
}
return $weeks;
}
and in the foreach I added
$x="1/1/2013 + ".$record->tms." weeks";
$m=date("Y-m-d", strtotime($x));
$first_week_start=getWeeks($m, "sunday");
if($first_week_start == 1){$typo="st";}
if($first_week_start == 2){$typo="nd";}
if($first_week_start == 3){$typo="rd";}
if($first_week_start == 4){$typo="th";}
if($first_week_start == 5){$typo="th";}
$month=date("M", strtotime($m));
$final_format .= "'".$first_week_start.$typo ." week in ".$month."'";
Try a loop, start with 1/jan, use DateInterval::createFromDateString('1 week'); and DateTime::add each time in the loop to add the next week, use DateTime::format to get the month also checking the current year in each iteration to make sure the loop hasn't moved to the next year.
Code:
date_default_timezone_set("UTC");
$weeks = array();
$dt = new DateTime("2013-01-01");
$interval = DateInterval::createFromDateString("1 week");
for($i=1; $i <= 52; $i++)
{
$weeks[$i] = "week " . $i . " " . $dt->format("M");
$dt = $dt->add($interval);
}
print_r($weeks);
If you want a function that will return a month abbreviation from a week:
function weekMonth($week)
{
date_default_timezone_set("UTC");
return (new DateTime("2013-01-01"))->add(DateInterval::createFromDateString($week." week"))->format("M");
}
echo weekMonth(6);

Categories