Home > Software engineering >  Carbon add hours issue
Carbon add hours issue

Time:04-08

I'm struggling to understand why Carbon addHours() is not returning the proper time.

This is what i have in my controller :

public function create(Request $request)
    {

        $locationId = $request->input('location_id');
        $beginningDate = $request->input('beginning_date');
        $beginningTime = $request->input('beginning_time');
        // $beginningDate = $request->input('beginning_date')->format('d-m-Y');
        // $beginningTime = $request->input('beginning_time')->format('H:m');
        $duration = $request->input('duration');

        $totalPrice=PriceList::where('duration_to_hours', $duration)->value('price');

        $reservationStartingDate = $beginningDate. ','.$beginningTime;

        $calculateReservationDates = Carbon::parse($reservationStartingDate)->addHours($duration);

        $endDate= $calculateReservationDates->format('d-m-Y');
        $endTime = $calculateReservationDates->format('H:m');

       $reservedCount = Reservation::where('beginning_date', '>=', $endDate)
       ->where('end_date', '>=', $beginningDate )
       ->where('beginning_time', '<=', $endTime)
       ->where('end_time', '>=', $beginningTime)
       ->count();

       

        $totalBoxes = Box::where('location_id', $locationId)->count();

        dd($endDate, $endTime);

        $available = false;

        if($reservedCount < $totalBoxes){
            $available = true;
        }


        return view('checkout', compact('locationId', 'totalPrice', 'endDate', 'endTime', 'beginningDate', 'beginningTime', 'duration', 'available'));
    }

But if for example the beginning time is 10:50 am and the duration is one hour, based on my logic it should return the $endTime to be 11.50 but it's only returning 11.04.

I do not get what I'm missing, do you have any idea?

Thank you

UPDATE

Here's the dd() of $reservationStartingDate :

^ "2022-04-22,00:53" 

CodePudding user response:

I think the H:m is wrong it's should be like this

    $endTime = $calculateReservationDates->format('H:i');

m is refer to month not minute

I hope it's helpful

CodePudding user response:

// Y - year
// m - month - not minutes
// d - day
// H - hours in 24h format default UTC
// i - minutes
// s - seconds

$beginningDate = '2022-04-07';
$beginningTime = '10:30'; // 24h format UTC

// "2022-04-07 10:30" - you need this format
$reservationStartingDate = "$beginningDate $beginningTime";
 
$result = Carbon::createFromFormat('Y-m-d H:i', $reservationStartingDate)->addHours(1);

Result with an hour added

Carbon\Carbon @1649331000 {#1724
   date: 2022-04-07 11:30:00.0 UTC ( 00:00),
}
  • Related