Validate range of dates in php or jquery

3

How can I condition PHP 5 (or jquery) if I am within a range of dates? For example I want to condition the range of dates If it is within the range send a message "Within Period" Otherwise "Out of Period"

The fact is that the date I want to validate is 20-12-2001 and I want to know if it is within the period of 2016 to 2017

Example: 20-12-2001 from 20-12-2015 to 2016 "Out of period";                       from 12-20-2016 to 2017 "Within the period"

Thank you.

    
asked by Juan Pablo Bustamante Luna 26.12.2016 в 20:31
source

2 answers

3

I will propose two possible solutions with PHP.

When you always use the same date format

If your dates are always in the day-month-year format you can use the explode function from PHP to get the year and perform the condition:

$fecha = "20-12-2001";
$fechaDividida = explode("-", $fecha);
$anno = $fechaDividida[2];

if ($anno >= 2016 && $anno <=2017){
    echo "Está dentro del periodo";
}else{
    echo "Está fuera del periodo";
}

It will return Está fuera del periodo for this specific case.

When you use different date formats

In this case you can use the strtotime function along with the date feature to get the year and then compare it to see if is within the range:

$fecha = "20-12-2001";
$anno = date('Y', strtotime($fecha));

if ($anno >= 2016 && $anno <=2017){
    echo "Está dentro del periodo";
}else{
    echo "Está fuera del periodo";
}

It will return Está fuera del periodo for this specific case.

In the latter case you could use $fecha = "2001-12-20"; and it would give you the same result. Even $fecha = "2001/12/20"; or $fecha = "20/12/2001"; and the result would be the same.

    
answered by 26.12.2016 / 20:37
source
0

You can use the class DateTime and check out with ->format("Y") the year and so check the dates:

$fecha1 = new DateTime('20-12-2001');
$fecha1 = $fecha1->format("Y"); //=> 2001
$fecha2 = new DateTime('20-12-2016');
$fecha2 = $fecha2->format("Y"); //=> 2016

$fechaInicio = new DateTime('20-12-2015');
$fechaInicio = $fechaInicio->format("Y"); //=> 2015
$fechaFin = new DateTime('01-01-2017');
$fechaFin = $fechaFin->format("Y");  //=> 2017

// Creamos una función para comprobar las fechas si están en el rango
function comprobarFecha($fecha, $fechaInicio, $fechaFin) {

    return $fecha >= $fechaInicio && $fecha <= $fechaFin;
}

// FECHA 1: 2001
if (comprobarFecha($fecha1, $fechaInicio, $fechaFin)) {

    echo 'Esta dentro del periodo';

} else {

    echo 'Esta fuera del periodo'; // <= Resultado
}    

// FECHA 2: 2016
if (comprobarFecha($fecha2, $fechaInicio, $fechaFin)) {

    echo 'Esta dentro del periodo'; // <= Resultado

} else {

    echo 'Esta fuera del periodo';
}

See Demo

    
answered by 26.12.2016 в 20:59