Error range dates php DateTime

1

I get the following error, I'm trying to do a range filter by dates, I'm using CodeIgniter 3x , I send the following dates by AJAX to PHP :

$fecha1 = 21/07/2017;
$fecha2 = 21/07/2017;

In this way I separate the date from the example field: 21/07/2017 - 22/07/2017 , so I read is that by making the split remains as a string , how would I have to convert it to date ?

JS :

  var str = value.split("-");
  var rango1= $.trim(str[0]);
  var rango2= $.trim(str[1]);

      var ParamObjSend={
             'fecha_rango1' : rango1,   
             'fecha_rango2' : rango2,               
      }

Verify that the data correctly arrives at PHP .

The error marks me on the line:

$fecha_reserva1 = new DateTime($fecha1);
  

Message: DateTime :: __ construct (): Failed to parse time string   (07/21/2017) at position 0 (2): Unexpected character

public function RangoFecha(){

    $fecha1                                  =$this->input->post('fecha_rango1');
    $fecha2                                  =$this->input->post('fecha_rango2');
    $fecha_reserva1                          =new DateTime($fecha1);
    $fecha_reserva2                          =new DateTime($fecha2);
    $Where['agenda.fecha_reserva>=']  =date_format($fecha_reserva1,'Y-m-d');
    $Where['agenda.fecha_reserva<=']  =date_format($fecha_reserva2,'Y-m-d');

    $Where['agenda.tipo']='Cita';
    $resultado = $this->Model->ListarAgenda($Where);
}
    
asked by Javier Antonio Aguayo Aguilar 21.07.2017 в 21:54
source

1 answer

0

The error appears because DateTime , does not understand the format in which the date is found.

Solution:

You could use DateTime::createFromFormat to pause the date.

Example:

public function RangoFecha(){

    $fecha1                           =$this->input->post('fecha_rango1');
    $fecha2                           =$this->input->post('fecha_rango2');
    $fecha_reserva1                   =DateTime::createFromFormat('d/m/Y', $fecha1);
    $fecha_reserva2                   =DateTime::createFromFormat('d/m/Y', $fecha2);
    $Where['agenda.fecha_reserva>=']  =$fecha_reserva1->format('Y-m-d');
    $Where['agenda.fecha_reserva<=']  =$fecha_reserva2->format('Y-m-d');

    $Where['agenda.tipo']='Cita';
   $resultado = $this->Model->ListarAgenda($Where);
}

-

With respect to the split that you use to obtain the dates, if the string is exactly this 21/07/2017 - 22/07/2017 , then the correct thing would be to make " - " ( with a space before and after the hyphen -middle ).

Demo:

var fechas = '21/07/2017 - 22/07/2017';
console.log('Split por "-"', fechas.split('-'), " deja espacios en las fechas");
console.log('Split por " - "', fechas.split(' - '), "no dejas espacios");
    
answered by 21.07.2017 / 22:17
source