Skip to content

Instantly share code, notes, and snippets.

@mrl22
Created October 23, 2023 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrl22/e9052655d5d695e328132ece218c0edf to your computer and use it in GitHub Desktop.
Save mrl22/e9052655d5d695e328132ece218c0edf to your computer and use it in GitHub Desktop.
Laravel / PHP / Carbon - Round time to the nearest X minutes.
<?php
namespace App\Helpers;
use Carbon\Carbon;
class TimeHelper
{
public static function round($time = null, $nearestMinutes = 15)
{
try {
$time = Carbon::parse($time);
$minutes = $time->minute;
$minutes = $minutes % $nearestMinutes;
if ($minutes < ($nearestMinutes / 2)) {
$time->subMinutes($minutes);
} else {
$time->addMinutes($nearestMinutes - $minutes);
}
return $time;
} catch (\Exception $e) {
return null;
}
}
public static function roundUp($time = null, $nearestMinutes = 15)
{
try {
$time = Carbon::parse($time);
$minutes = $time->minute;
$minutes = $minutes % $nearestMinutes;
if ($minutes > 0) $time->addMinutes($nearestMinutes - $minutes);
return $time;
} catch (\Exception $e) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment