Laravel中如何将两个Carbon日期相加?
Hey there! Let's break this down because when you say "add two Carbon dates", we need to clarify what exactly you mean—since Carbon instances represent specific points in time, adding two points together doesn't really make sense (like, what's 2024-05-20 10:15:00 + 2024-05-19 08:30:00? Probably not what you're after).
First, let's align on the context: your $date1 is created from a time string (H:i:s) plus 15 minutes, which means it's a Carbon instance tied to today's date with that adjusted time. Your $date_two is likely a full datetime value (e.g., 2024-05-20 08:30:00) from your model.
Assuming your goal is either:
- Add the duration represented by
$date1(e.g., if$date1is10:15:00, that's 10 hours and 15 minutes) to$date_two, OR - Replace the time portion of
$date_twowith the time from$date1
Here's how to handle both scenarios:
First, ensure $date_two is a Carbon instance
If your model doesn't already cast filed_departuretime to a datetime (check your model's $casts property), convert it first to avoid errors:
$date_two = \Carbon\Carbon::parse($status_info->filed_departuretime);
Option 1: Add the duration from $date1 to $date_two
Since $date1 is based on today's date, we can extract its hours, minutes, and seconds and add them directly to $date_two:
// Use copy() to avoid modifying the original $date_two variable (Carbon is mutable!) $result = $date_two->copy() ->addHours($date1->hour) ->addMinutes($date1->minute) ->addSeconds($date1->second);
Alternatively, you can calculate the total seconds since midnight for $date1 and add that in one step:
$totalSeconds = $date1->diffInSeconds(\Carbon\Carbon::today()->startOfDay()); $result = $date_two->copy()->addSeconds($totalSeconds);
Option 2: Set the time of $date_two to match $date1
If you want to keep the date from $date_two but use the exact time from $date1:
$result = $date_two->copy() ->setTime($date1->hour, $date1->minute, $date1->second);
A quick reminder: always use copy() when modifying Carbon instances unless you explicitly want to alter the original variable—Carbon's mutability can lead to unexpected side effects if you skip this step.
内容的提问来源于stack exchange,提问作者wandie

