This tutorial will show you how to get the individual working dates of a month, whilst removing weekends, this is useful for creating charts for instance.
First create an empty array it will later store the dates.
$workdays = array();
<p>Next I'm making use of a native function to inform php which type of calendar were working this, in this case its an Gregorian Calendar</p>
$type = CAL_GREGORIAN;
Next set the current month and year and get the total number of days in the current month using another inbuilt function: cal_days_in_month.
$month = date('n'); // Month ID, 1 through to 12.
$year = date('Y'); // Year in 4 digit 2009 format.
$day_count = cal_days_in_month($type, $month, $year); // Get the amount of days
Next create a for loop to loop through the number of days of the month then format the date for each day extract the day name and check the day is not a Sun or Sat then add that date to an array called $workdays
//loop through all days
for ($i = 1; $i <= $day_count; $i++) {
$date = $year.'/'.$month.'/'.$i; //format date
$get_name = date('l', strtotime($date)); //get week day
$day_name = substr($get_name, 0, 3); // Trim day name to 3 chars
//if not a weekend add day to array
if($day_name != 'Sun' && $day_name != 'Sat'){
$workdays[] = $i;
}
}
From here you've got all the dates stored in an array to use.
To just see the array contents we can use print_r:
print_r($workdays);
To use the array you could use a foreach:
foreach ($workdays as $key=>$value) {
//do something here
}
Here's the full script:
$workdays = array();
$type = CAL_GREGORIAN;
$month = date('n'); // Month ID, 1 through to 12.
$year = date('Y'); // Year in 4 digit 2009 format.
$day_count = cal_days_in_month($type, $month, $year); // Get the amount of days
//loop through all days
for ($i = 1; $i <= $day_count; $i++) {
$date = $year.'/'.$month.'/'.$i; //format date
$get_name = date('l', strtotime($date)); //get week day
$day_name = substr($get_name, 0, 3); // Trim day name to 3 chars
//if not a weekend add day to array
if($day_name != 'Sun' && $day_name != 'Sat'){
$workdays[] = $i;
}
}
// look at items in the array uncomment the next line
//print_r($workdays);
Subscribe to my newsletter for the latest updates on my books and digital products.
Find posts, tutorials, and resources quickly.
Subscribe to my newsletter for the latest updates on my books and digital products.