Problem when paging data from a DateRangePicker

1

I have a daterangepicker:

$( function() {
$( 'input[name="datefilter"]').daterangepicker({
    changeMonth: true,
    autoUpdateInput: false,
    showButtonPanel: true,
    dateFormat: 'mm/dd/yyyy',
    numberOfMonths: 2,
    regional: 'es',
    locale:{
      "fromLabel": "From",
      "toLabel": "To",
      "customRangeLabel": "Custom",
      "daysOfWeek": ["Lun","Mar","Mie","Jue","Vie","Sa","Dom"],
      "monthNames": ["Enero","Febrero", "Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],
      applyLabel: 'Guardar',
      cancelLabel: 'Limpiar',
      monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'],
      dayNamesShort: ['Dom','Lun','Mar','Mié','Jue','Vie','Sáb'],
    }
});
$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
  $(this).val(picker.startDate.format('DD/MM/YYYY') + ' - ' + picker.endDate.format('DD/MM/YYYY'));
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
  $(this).val('');
}); 
  });
  </script>

Which, after the controller method, I get the date correctly:

 public function store(Request $request)
{
    $this->validate($request, [
        'type' => 'required',
        'observations' => 'required',
        'datefilter' => 'required',
    ]);

    $dep =\DB::table('users')->select('users.area_id')
        ->where(['users.id' => $request->user_id])
        ->get(); 

     //parse dates
    $date  = explode('-',$request['datefilter']);

    $dateFrom = date("dd-mm-yyyy",strtotime( $date[0]));
    $dateTo = date("dd-mm-yyyy",strtotime($date[1]));

    $vacation = new Vacation();
    $vacation -> user_id = $request['user_id'];
    $vacation -> type = $request['type'];
    $vacation -> observations = $request['observations'];
    $vacation -> area_id = $dep[0]->area_id;
    $vacation -> date_from = date("y-m-d", strtotime($dateFrom));
    $vacation -> date_to = date("y-m-d", strtotime( $dateTo ));
    //$vacation -> daysTaken = $daysTaken;

dd($date[0]->format('Y-m-d'));

$guardadas = \DB::table('vacations')->where(function($q) use ($dateFrom, $dateTo) {
        // ambas dentro del rango/periodo
                $q->where('date_from', '>=', $dateFrom)
                  ->where('date_to', '<=', $dateTo);
        })->orWhere(function($q) use ($dateFrom, $dateTo) {
        // fin desborda rango/periodo pero inicio dentro rango/periodo
                $q->where('date_from', '>=', $dateFrom)
                  ->where('date_to', '>', $dateTo);
        })->orWhere(function($q) use ($dateFrom, $dateTo) {
        // inicio desborda rango/periodo pero fin dentro de rango/periodo
            $q->where('date_from', '<', $dateFrom)
              ->where('date_to', '<=', $dateTo);
        })->orWhere(function($q) use ($dateFrom, $dateTo) {
        // inicio y fin desbordan el rango/periodo
            $q->where('date_from', '<', $dateFrom)
              ->where('date_to', '>', $dateTo);
        })// otras condiciones
        ->get();

        //dd($guardadas);

        if($vacation->date_from != $guardadas[0]->date_from and $vacation->date_to != $guardadas[0]->date_to||
           $vacation->area_id != $guardadas[0]->area_id){

           $vacation->save();

            $data = request()->all();

           return back()->with('success','Vacaciones Solicitadas correctamente');

        }else{
            return back()->with('error','Fechas no disponibles');
        }

        return back();
    }

My problem comes when trying to pause the dates to make the difference of days, to know for example that the user has selected 10 days, between the first and the last, try with Carbon, and with createFormat and diffs , the php methods themselves, but all give me syntax error say the time because it is not properly formatted, and I do not know what else to try, I have debugged all the variables and tried to format them, but I have not been able, I put the different outputs that I have been seeing with dd, I would appreciate a little hand with this.

The functions that I have used are these, I did not put them in the method because I gave an error all the time:

 $datetime1 = new DateTime($date[0]);
    $datetime2 = new DateTime($date[1]);
    $interval= $datetime1->diff($datetime2);
    $days = $interval->format('dd-mm-yyyy');

And the other:

   $format = 'dd-mm-yyyy';
    $d1 = Carbon::createFromFormat($date[0],$format);
    $d2 = Carbon::createFromFormat($date[1],$format);
    //$days = $d1->diff($d2)->days;

    $daysTaken = $d2->diffInDays($d1);

And the error this:

DateTime::__construct(): Failed to parse time string (27/08/2018 ) at position 0 (2): Unexpected character

And now what I find more redundant is that I change the format to put it to the object, and apart I wanted to see the difference to know how many days it took and calculate the difference, I saw that it could be done in javascript, but I I was throwing the same mistakes.

Thank you very much for your attention. Greetings.

Edit: date correctly formatted as: "dd-mm-yyyy"

I have also used this method of carbon: which gives me the following error: Method:

$date  = explode('-',$request['datefilter']);
    $dateFrom = str_replace('/', '-', $date[0]);
    $dateTo = str_replace('/', '-', $date[1]);

    $start_date = Carbon::parse($date[0]);
    $end_date = Carbon::parse($date[1]);
    $diff = $start_date->diffInDays($end_date);

error:

DateTime::__construct(): Failed to parse time string (22/08/2018 ) at position 0 (2): Unexpected character

Edit2:

$date  = explode('-',$request['datefilter']);
    $dateFrom = str_replace('/', '-', $date[0]);
    $dateTo = str_replace('/', '-', $date[1]);
    $inicio = DateTime::createFromFormat('d/m/Y', $date[0]);
    //echo $inicio->format('Y-m-d');
    $fin = DateTime::createFromFormat('d/m/Y', $date[1]);
    dd($date[0]);
    //echo $fin->format('Y-m-d');
    $diff = date_diff($inicio, $fin);
    // Mostramos la diferencia
    dd($dif->format('%R%a días'));
    
asked by Peisou 16.08.2018 в 16:42
source

1 answer

1

Since the date is not in the expected standard format, you need to pause it so that DateTime interprets it correctly. For this the class DateTime gives us the method createFromFormat() .

Let's see an example of use:

$date[0] = "27/08/2018";
$date[1] = "28/08/2018";

$inicio = DateTime::createFromFormat('d/m/Y', trim($date[0]));
echo $inicio->format('Y-m-d');

$fin = DateTime::createFromFormat('d/m/Y', trim($date[1]));
echo $fin->format('Y-m-d');

// Diferencia de fechas 
$diff = date_diff($inicio, $fin);
// Mostramos la diferencia
echo $diff->format('%R%a días'); // +1 días

Documentation:

DateTime :: createFromFormat ()

DateTime :: diff ()

    
answered by 16.08.2018 / 17:37
source