Search code examples
phpdatedatetime-formatphp-carbon

how can I add some hours in PHP/Carbon?


I am using Laravel and have this code:

$date = now()->locale('es_ES');

$start_date = $date->isoFormat('D [de] MMMM [de] YYYY')
$start_time = $date->isoFormat('HH[H]hh')
$end_date =  $date->addHours(3)->isoFormat('D [de] MMMM [de] YYYY')
$end_time =  $date->addHours(3)->isoFormat('HH[H]hh')

this is the output

start_date : 24 de abril de 2023 start_time : 21H09
end_date : 25 de abril de 2023 end_time: 03H03

I would like the end date and time to be something like this:

end_date: 25 de abril de 2023 end_time: 00H09

it looks like it is adding more then 3 hours, and also the minutes is different, what is happening? thanks


Solution

  • If you want minute, you need mm instead of hh, then you should copy the date and add hours only once:

    $date = now()->locale('es_ES');
    
    $start_date = $date->isoFormat('D [de] MMMM [de] YYYY');
    $start_time = $date->isoFormat('HH[H]mm');
    
    $end = $date->copy()->addHours(3);
    
    $end_date =  $end->isoFormat('D [de] MMMM [de] YYYY');
    $end_time =  $end ->isoFormat('HH[H]mm');
    

    (note that now() is creating a mutable Carbon object, switch to CarbonImmutable to have immutable instead is also an option)