Created
September 3, 2021 20:16
-
-
Save heyodai/56ed0f7b6a00d909ec1d0f432c791d5c to your computer and use it in GitHub Desktop.
Unfinished attempt at converting duration strings to DateInterval objects
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 | |
/** | |
* Take duration string from a database - e.g. 00:21:15.2581 - and convert it to | |
* a DateInterval object (PHP's built-in duration object). | |
* | |
* DateInterval does not support construction from these strings directly, which | |
* is why this function is needed. | |
* | |
* Supported units are years, months, days, hours, minutes, and seconds. | |
* Weeks and microseconds are not currently supported. | |
* | |
* @param string $duration_string The duration to convert from | |
* @return DateInterval object of correct duration | |
* | |
* @see https://www.php.net/manual/en/dateinterval.construct.php | |
*/ | |
function createDateIntervalFromDurationString($duration_string) { | |
$duration_array = explode(':', $duration_string); // e.g. 00:21:15.2581 | |
$array_size = count($duration_array); | |
$construction_string = ''; | |
$operator_array = [ | |
'S', // seconds | |
'M', // minutes | |
'H', // hours | |
'D', // days | |
'M', // months | |
'Y' // years | |
]; | |
$j = 0; | |
for ($i = $array_size; $i >= 0; $i--) { | |
$construction_string = (round($duration_array[$i]).$operator_array[$j]) . $construction_string; | |
$j++; | |
} | |
$construction_string = 'P' . $construction_string; | |
return new DateInterval($construction_string); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment