skip to Main Content

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

2

Answers


  1. 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->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)

    Login or Signup to reply.
  2. I think you’re looking for something like this:

        $start = now()->locale('es_ES');
        $end = $start->copy()->addHours(3);
        
        $start_date = $start->isoFormat('D [de] MMMM [de] YYYY');
        $start_time = $start->isoFormat('HH[H]hh');
        $end_date = $end->isoFormat('D [de] MMMM [de] YYYY');
        $end_time = $end->isoFormat('HH[H]hh');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search