Created
October 23, 2023 16:31
-
-
Save mrl22/e9052655d5d695e328132ece218c0edf to your computer and use it in GitHub Desktop.
Laravel / PHP / Carbon - Round time to the nearest X minutes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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