Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

maplerock's avatar

Update date to different date

If I have the below. Where I want to update a date. In the DB it is 01/02/2018 and I want to update to the value the "new date" 15/02/2018. How can I do this? Am I being stupid I can't find anything online

$request->new_date //2018-02-15
$session->start_date //carbondate: 2018-02-01 10:30:00.0 UTC (+00:00)
$session->start_date->modify($request->new_date) //Is that right?
0 likes
6 replies
maplerock's avatar

So I've got to the below - is there a more elegant way?

 $date_parts = explode('-',$request->new_date);

$session->start_date = $session->start_date->setDate($date_parts[0], $date_parts[1], $date_parts[2]);
rawilk's avatar

Why wouldn't you just do: $session->start_date = $request->new_date;?

1 like
maplerock's avatar

Because I need to keep the time element intact I only want to update the d/m/Y part. Basically saying move this start time to another date...

rawilk's avatar

Well, there's no need to explode the new date, just use Carbon to parse the new date and set the date from there.

2 likes
skliche's avatar
skliche
Best Answer
Level 42

A bit more readable

$newDate = new \Carbon\Carbon($request->new_date);
$session->start_date->setDate($newDate->year, $newDate->month, $newDate->day);

Please or to participate in this conversation.