Doubt with DateTime

0

I have an application where the employee can make vacation requests. Well my problem comes when I want to choose back dates. Let me explain myself better, I have this if :

if($fecha_inicio < $fecha_solicitud){
    echo "Start date can not be less than today's date";
}

This if says that if the date on which you want to start the vacation is less than the date of the request (today), you should miss an error.

Each date is of type DateTime . With this if it makes me perfect that they can not catch days behind. The problem comes with the time, for example:

If when the user makes the request is 12:00 today, and the user, because he is sick, takes the holiday today. The user must be taken today from 8:00 in the morning. That's when I get the error, the time is less and I do not want to take into account the time, only the day. Any help?

    
asked by Xerox 14.03.2018 в 15:16
source

2 answers

1

Try this:

if($fecha_inicio < $fecha_solicitud &&
   $fecha_inicio->format('d-m-Y') !== $fecha_solicitud->format('d-m-Y')){
     echo "End date can not be less than start date";
}

Thus only the error will jump if start_date is less than the request date and are of different days, so the subject of the time no longer matters

    
answered by 14.03.2018 / 15:29
source
0

You can compare the DateTime objects based on a format in which the time is not taken into account.

Let's see this function, which receives two objects to compare. Both objects apply format('Y-m-d') and then you can compare.

In my opinion, you should not only compare using the operator < , but you should put <= .

function compararFechas($fechaInicio,$fechaSolicitud){
    if ( $fechaInicio->format('Y-m-d') <= $fechaSolicitud->format('Y-m-d')){
        echo "Start date: ".$fechaInicio->format('Y-m-d') ." can not be less or equal than today's date: ".$fechaSolicitud->format('Y-m-d').PHP_EOL;
    }else{
        echo "You can apply for vacations starting at: ".$fechaInicio->format('Y-m-d')."!".PHP_EOL;
    }
}

Test the code

VIEW DEMO IN REXTESTER

We are going to do several tests of our function:

$fechaSolicitud = new DateTime('now');

/*Prueba 1*/
$fechaInicio = new DateTime('2018-03-15 16:20:07.900');
compararFechas($fechaInicio,$fechaSolicitud);


/*Prueba 2*/
$fechaInicio = new DateTime('2018-03-14 10:20:07.900');
compararFechas($fechaInicio,$fechaSolicitud);

/*Prueba 3*/
$fechaInicio = new DateTime('2018-03-14 17:50:07.900');
compararFechas($fechaInicio,$fechaSolicitud);

/*Prueba 4*/
$fechaInicio = new DateTime('2011-03-14 17:50:07.900');
compararFechas($fechaInicio,$fechaSolicitud);

This would be the exit for the four tests:

You can apply for vacations starting at: 2018-03-15!
Start date: 2018-03-14 can not be less or equal than today's date: 2018-03-14
Start date: 2018-03-14 can not be less or equal than today's date: 2018-03-14
Start date: 2011-03-14 can not be less or equal than today's date: 2018-03-14
    
answered by 14.03.2018 в 16:41