How to add 1 hour to date Carbon?
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
The Carbon library provides extensive support for working with dates and time in PHP. To add an hour to a specific datetime, there are various approaches you can take. In this blog post, we will go through the correct ways to perform such operations and understand how to compare the adjusted date with the current one.
Using the addHour() Method
Similar to our initial attempt as shown above, you can use the addHour() method directly on a carbon instance. In this case, it would be applied to the given datetime string:
$dateTime = Carbon::createFromFormat('Y-m-d H:i:s', '2016-11-24 11:59:56');
$newDateTime = $dateTime->addHour();
However, there are a couple of things to keep in mind:
- Formatting and Conversions: The
createFromFormat()method used here will parse the given date string into a carbon instance. You should be cautious about the format you use, as different formats may produce inconsistent results. - Timezone Considerations: Carbon instances are timezone-aware, so make sure to set the desired timezone before using any date manipulation methods.
Creating a Custom Time Function
Another approach would be creating a custom function that adds one hour to the given datetime. This can be useful for cases where you will be comparing the adjusted time with the current time multiple times.
function addOneHourToDateTime($dateTime) {
return Carbon::createFromFormat('Y-m-d H:i:s', $dateTime)->addHour();
}
This function would accept a carbon or datetime string and return the adjusted date. It can be called as:
$newDateTime = addOneHourToDateTime('2016-11-24 11:59:56');
Comparing Adjusted and Current Datetimes
Comparing the adjusted datetime with the current one is a relatively straightforward process. You can use the diffInMinutes() method to get the time difference between two dates in minutes:
$diff = $newDateTime->diffInMinutes(now());
if ($diff == 60) {
// One hour has passed
}
This code block checks whether the difference between the adjusted and current time is equal to one hour. If it's exactly 60 minutes, that means the given datetime has become one hour older in comparison with the current time.
In conclusion, there are various ways to add an hour to a specific date using Carbon's powerful functionalities. The most efficient approach depends upon your needs and what you want to accomplish. For a quick modification of a single date, theaddHour() method works fine. In case you need to perform this operation multiple times or compare the adjusted time with the current one, creating a custom function might be helpful. Always keep in mind formatting and conversions, and ensure that your code reflects your application's requirements.