How to discount the days of the weekend

2

I have the following code where I count the differences of days, but I want to discount the weekends

<?php
$datetime1 = new DateTime($machine->fechasolicitud);
$datetime2 = new DateTime($machine->fecha);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a días');
?>

Is there any way in PHP or MySql?

    
asked by MoteCL 12.07.2018 в 16:26
source

2 answers

3

An approximation in php with dates in date format is with a loop that runs through the period and asks about the day of the week:

$counter = 0; 
$fecha1= "2018-01-01"; $fecha2 = "2018-01-31"; //ejemplo de fechas
for($i=$fecha1; $i<$fecha2; $i = date("Y-m-d", strtotime($i ."+ 1 days"))) {
   if (date("w",strtotime($i)) != 5 && date("w",strtotime($i)) != 6) { $counter++;}
}
echo $counter;
    
answered by 12.07.2018 / 16:44
source
0

To make it a little more automated taking Carmen's answer as reference, you can do it this way:

<?php

$fsis = date("Y m d h i a");

list($sano, $smes, $sdia, $shora, $smin, $sap ) = explode(" ", $fsis);


$contador = 0; 
$fecha = new DateTime();
$fecha->modify('last day of this month');


$fecha1 = $sano . "-" . $smes . "-" . $sdia; $fecha2 = $sano . "-" . $smes . "-" . $fecha->format('d');
for($i=$fecha1;$i<=$fecha2;$i = date("Y-m-d", strtotime($i ."+ 1 days"))) {
   if (date("w",strtotime($i)) != 5 && date("w",strtotime($i)) != 6) { $contador++;}
}
echo $contador;


?>

This way you take the dates of the server and subtract them with the date of the month that is in course, that although some months can bring 31 days other months, not so you leave the automated process for any month of the year, you can subtract it with the current day and if you want to subtract the global month you can delete the variable sdia to take you day 1 only.

I hope it serves you and the community that needs it, greetings.

    
answered by 12.07.2018 в 17:37