Find Minute, Hour Difference using Carbon in PHP

Yanuar Arifin
2 min readMar 25, 2021
Photo by Aron Visuals on Unsplash

strtotime would give you full timestamp, and its not straightforward(for me) to find minute/hour/day (or any number of minute) difference. I propose using Carbon library because it is easier and this library has been proven and maintained.

The Problem

I have 2 commands that needs to run every 15 minutes alternating between 2 different date range parameter. I wrangled with strtotime for some time without any solution, then thought that this app(Laravel) has Carbon library. Surely they must have classes and features for comparison like this. So I read their documentation and found what I was looking for. Checkout the diffInMinutes() function, search by Ctrl + f on your browser.

Solution

This is how I approach it:

  • Create a carbon instance as an anchor. No particular value, just make it in the past.
  • create a new carbon instance using current datetime.
  • Get the difference using diffInMinutes() function.
  • Use modulus to check if 15 minutes has passed, for odd even difference, add additional condition using modulus 2.
<?
use Carbon\Carbon;
# Create anchor time and another date time to be compared
$anchorTime = Carbon::createFromFormat("Y-m-d H:i:s", "2021-03-01 00:00:00");
$currentTime = Carbon::createFromFormat("Y-m-d H:i:s", date("Y-m-d H:i:00"));
# count difference in minutes
$minuteDiff = $anchorTime->diffInMinutes($currentTime);
if($minuteDiff % 15 == 0 && $minuteDiff % 2 ==0 ){
echo "15 minutes even";
}
if($minuteDiff % 15){
echo "15 minutes odd";
}

That is it. Faster than using strtotime and figuring out minute difference(should I multiply 15 by 60 or 3600? How to compensate when it just differ a few second?). Those questions handled by Carbon.

Possible Diffs

Below is the list of possible difference that I found after skim through its documentation. Do visit it if you think what you need is not found below.

echo $anchorTime->diffInSeconds($currentTime);
echo $anchorTime->diffInMinutes($currentTime);
echo $anchorTime->diffInHours($currentTime);
echo $anchorTime->diffInDays($currentTime);
echo $anchorTime->diffInDays($currentTime);
echo $anchorTime->diffInWeekdays($currentTime);
echo $anchorTime->diffInWeekendDays($currentTime);
echo $anchorTime->diffInWeeks($currentTime);
echo $anchorTime->diffInMonths($currentTime);
echo $anchorTime->diffInQuarters($currentTime);
echo $anchorTime->diffInYears($currentTime);

Conclusion

Do not reinvent the wheel, use what is easiest, especially if it already present(not adding another dependencies). Libraries are created to ease our development process using certain language. But use reputable ones.

--

--

Yanuar Arifin

Software Engineer. Currently PHP. How far could we automate things?