0

I'm trying to convert a string of the format "HH:MM" (for example, 01:25 - 1 hour and 25 minutes), for usage as microdata in a recipe page.

I can create a DateTime object from the string like so:

$time = date_create_from_format("H:i", get_field("tilberedningstid"));

But how do I convert this DateTime object to a legit ISO8601 duration format?

I feel like I've tried everything. I played around with the DateInterval class, which should output (I think?) the right format, which would be PT1H25M, but I can't seem to convert my DateTime object to a format, that DateInterval can interpret. I've already tried $interval = DateInterval($time->format(DateTime::ISO8601));, which should be supported by the DateInterval class.

So the questions is simple: How do I convert a string "01:25" (HH:MM) to an ISO8601-string PT1H25M for usage in microformat, in php?

MadsMadsDk
  • 117
  • 1
  • 3
  • 13

1 Answers1

2

Why are you using the date interval? You can just use format. But because the PTHM chars are also valid codes, you must escape them.

<?php
$date = new DateTime('01:25');
echo $date->format('\P\TG\Hi\M');
//output: PT1H25M
?>

See date for valid codes and DateTime::format for how to use them

Hugo Delsing
  • 13,803
  • 5
  • 45
  • 72
  • 1
    Of course, how silly of me. I guess I was mislead by the documentation [here](http://php.net/manual/en/dateinterval.format.php) - thanks :) This works like a charm! – MadsMadsDk May 07 '13 at 12:00