What is the best way to calculate workdays within a given time period using PHP?
To calculate workdays within a given time period using PHP, you can loop through each day in the time period and check if it falls on a weekend (Saturday or Sunday). If it does not fall on a weekend, increment a counter for workdays. Here is a PHP code snippet to achieve this:
function getWorkdays($start_date, $end_date) {
$workdays = 0;
$current_date = strtotime($start_date);
$end_date = strtotime($end_date);
while ($current_date <= $end_date) {
if (date('N', $current_date) < 6) { // Check if the current day is not a weekend
$workdays++;
}
$current_date = strtotime('+1 day', $current_date);
}
return $workdays;
}
$start_date = '2022-01-01';
$end_date = '2022-01-31';
echo "Number of workdays between $start_date and $end_date: " . getWorkdays($start_date, $end_date);
Keywords
Related Questions
- What is the difference between using type="text" and type="hidden" in a form field in PHP?
- How can one ensure that placeholder elements are not mistakenly identified within HTML comments or JavaScript code when using regular expressions in PHP?
- What is the purpose of using mysqli_real_escape_string in the provided PHP code?