In this blog, I will show you the total number of weeks available in a month, ie.., here we will get each week dates in a month from Monday to Saturday. We need to pass the month and year to get the start date and end date of a week. If we need the number of weeks then in the index will start from zero, just increment the value of index using index++ using for each loop, then you will get the week number as well. Using the below code you will get week number and dates in a week easily, but don`t forget to pass month and year. This code is applicable to PHP only.
public static function getWeeks($month,$year)
{
$month = intval($month);
$suff = array('st','nd','rd','th','th','th');
$end = date('t',mktime(0,0,0,$month,1,$year));
$start = date('w',mktime(0,0,0,$month,1,$year));
$last = 7 - $start;
$noweeks = ceil((($end - ($last + 1))/7) + 1);
$output = "";
$monthlabel = str_pad($month, 2, '0', STR_PAD_LEFT);
$monWeek = [];
for($x=1;$x<$noweeks+1;$x++){
if($x == 1){
$startdate = "$year-$monthlabel-01";
$day = $last - 6;
}else{
$day = $last + 1 + (($x-2)*7);
$day = str_pad($day, 2, '0', STR_PAD_LEFT);
$startdate = "$year-$monthlabel-$day";
}
if($x == $noweeks){
$enddate = "$year-$monthlabel-$end";
}else{
$dayend = $day + 6;
$dayend = str_pad($dayend, 2, '0', STR_PAD_LEFT);
$enddate = "$year-$monthlabel-$dayend";
}
$ar = array("start_date"=>$startdate,"end_date"=>$enddate);
array_push($monWeek, $ar);
}
return $monWeek;
}
public static function getWeeks($month,$year)
{
$month = intval($month);
$suff = array('st','nd','rd','th','th','th');
$end = date('t',mktime(0,0,0,$month,1,$year));
$start = date('w',mktime(0,0,0,$month,1,$year));
$last = 7 - $start;
$noweeks = ceil((($end - ($last + 1))/7) + 1);
$output = "";
$monthlabel = str_pad($month, 2, '0', STR_PAD_LEFT);
$monWeek = [];
for($x=1;$x<$noweeks+1;$x++){
if($x == 1){
$startdate = "$year-$monthlabel-01";
$day = $last - 6;
}else{
$day = $last + 1 + (($x-2)*7);
$day = str_pad($day, 2, '0', STR_PAD_LEFT);
$startdate = "$year-$monthlabel-$day";
}
if($x == $noweeks){
$enddate = "$year-$monthlabel-$end";
}else{
$dayend = $day + 6;
$dayend = str_pad($dayend, 2, '0', STR_PAD_LEFT);
$enddate = "$year-$monthlabel-$dayend";
}
$ar = array("start_date"=>$startdate,"end_date"=>$enddate);
array_push($monWeek, $ar);
}
return $monWeek;
}
Comments
Post a Comment