Skip to content

Instantly share code, notes, and snippets.

@heyodai
Created September 3, 2021 20:16
Show Gist options
  • Save heyodai/56ed0f7b6a00d909ec1d0f432c791d5c to your computer and use it in GitHub Desktop.
Save heyodai/56ed0f7b6a00d909ec1d0f432c791d5c to your computer and use it in GitHub Desktop.
Unfinished attempt at converting duration strings to DateInterval objects
<?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