Help php receive two dates and show the end of the month in red

3

I need help with that exercise, it's a web application with php . It has to be POO

Make an application that receives two dates and shows a list of the dates included in that range, showing the last day of each month of RED color.

I'm doing tests with this code but I do not know how to condition if it's the end of the month to put it in red

<?php

$hoy1=new DateTime("01-01-2018");

$fin=new DateTime("01-10-2018");
echo "<font color=#FF0000>"."ultimo día del mes es: 1"."</font>"."<br>";

for ($i=$hoy1; $i <$fin ; $i++) { 
    # code...
    echo $hoy1->format('d-m-Y')."<br>";

    $hoy1->modify('+1 days');

}
?>
    
asked by Aldo Silva 17.07.2018 в 17:16
source

2 answers

2
<?php
date_default_timezone_set("Europe/Madrid"); //OBLIGATORIO. Se define la zona horaria

$hoy=new DateTime("01-01-2018"); //La fecha de inicio
$fin=new DateTime("01-10-2018"); //La fecha de fin

while($hoy <= $fin) { //El bucle se ejecuta solamente si la fecha actual es menor o igual que la fecha de fin

    $ultimo_dia_mes = clone $hoy; //clonamos la variable $hoy para no machacar los cambios
    $ultimo_dia_mes->modify('last day of this month'); //Extraemos el ultimo dia del mes de la fecha actual
    if($ultimo_dia_mes == $hoy) { //Comprobamos que la la fecha actual es el ultimo dia del mes
        echo '<span style="color:red;">'.$hoy->format("d/m/Y").'</span><br>';
    } else {
        echo '<span style="color:green;">'.$hoy->format("d/m/Y").'</span><br>';
    }

    $hoy->modify('+1 days'); //añadimos un dia a la fecha actual
}
    
answered by 17.07.2018 / 18:40
source
5

I think this can help you, php has a function called cal_days_in_month, which gives you the number of days you have a month of a particular year, if you take that value and compare it with the day of the date evaluated in the moment, you can determine if it corresponds or not to the last day:

$hoy1=new DateTime("01-01-2018");

$fin=new DateTime("01-10-2018");
echo "<font color=#FF0000>"."ultimo día del mes es: 1"."</font>"."<br>";

for ($i=$hoy1; $i <$fin ; $i++) { 
    //Calculas cuantos dias tiene el mes del año en particular con esta funcion de php
    $ultimoDia = cal_days_in_month(CAL_GREGORIAN, $hoy1->format('m'), $hoy1->format('Y'));

    //Si el dia de la fecha actual concuerda con el ultimo dia, se imprime en rojo
    if($hoy1->format('d') == $ultimoDia){
        echo "<font color=#FF0000>"."ultimo día del mes es: ".$hoy1->format('d-m-Y')."</font>"."<br>";

    }else{
            echo $hoy1->format('d-m-Y')."<br>";
    }

    $hoy1->modify('+1 days');
}

I tried it, and it seems to be what you need

    
answered by 17.07.2018 в 17:38