0

Using PHP, I want to be able to go from a strtotime relative time to a datetime interval that can be used for an iCalendar duration.

An example would be something like:

$date = \DateInterval::createFromString('5 minutes');
$period = $date->doSomeMagic();
echo $period; // should echo "PT5M"

Are there any built-in PHP functions to do this? Or if there aren't, is there a library that can do it?

Algy Taylor
  • 814
  • 13
  • 29

1 Answers1

1

Perhaps something like this

$date = \DateInterval::createFromDateString('2 days 5 minutes');

function doSomeMagic(\DateInterval $date) {
    $interval = 'P' .
        ($date->y == 0 ? null : $date->y . 'Y') .
        ($date->m == 0 ? null : $date->m . 'M') .
        ($date->d == 0 ? null : $date->d . 'D');
    $timeInterval =
        ($date->h == 0 ? null : $date->h . 'H') .
        ($date->i == 0 ? null : $date->i . 'M') .
        ($date->s == 0 ? null : $date->y . 'S');
    return $interval . ((!empty($timeInterval)) ? 'T' . $timeInterval : null);
}


$period = doSomeMagic($date);
echo $period;
Mark Baker
  • 209,507
  • 32
  • 346
  • 385