Question

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?

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top