PHP & MySQL | Tutorials

David Carr

Show working days of a month excluding weekends with PHP

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);

 

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.