How to convert time duration in PT format to regular string in php

Viewed 880

I have data like following

PT45M
PT1H30M

How can i get an output like

45 min
1 hour 30 min

Is there any function in php to get output like shown?

    $dur="PT45M"; 
    $d = new DateInterval($dur);
    $duration=$d->format('%h hour %m min');
    $duration=str_replace(" 0 min", "",$duration );
    $duration=str_replace("0 hour", "",$duration );

This is one solution almost worked for me. But on PT45M it is showing 0 hour. :( It may be a simple function, but am unable to find a solution. Have spent a lot of time in googleing :( Hope someone can help me with this.

3 Answers

The solution is given below. I was using %m instead of using %i for minutes. (%m is for numeric month)

Here is the documentaion : https://www.php.net/manual/en/function.date.php

    $dur="PT45M"; 
    $d = new DateInterval($dur);
    $duration=$d->format('%h hour %i min');
    $duration=str_replace(" 0 min", "",$duration );
    $duration=str_replace("0 hour", "",$duration );

A function that creates a human-readable format from a DateInterval object:

function dateIntervalToHumanString(\DateInterval $interval) {
  $units = array("y"=>"year","m"=>"month","d"=>"day","h"=>"hour","i"=>"minute","s"=>"second");
  $specString = "";
  foreach($units as $prop => $spec){
    if($number=$interval->$prop){
      $specString .= $number." ".$spec;
      $specString .= $number > 1 ? "s " : " ";
    }  
  }
  return trim($specString); 
}

How to use it?

$specStr = 'P2Y4DT1H8M';
$di = new DateInterval($specStr);
$humanString = dateIntervalToHumanString($di);
echo $humanString;  //2 years 4 days 1 hour 8 minutes
     <?php
      $date = new DateTime();
      $dur="PT1H30M"; 
      $datetime1 = new DateInterval($dur);

      if($datetime1->format('%y') != 0)
      {
         echo $datetime1->format('%y Year');
      }
      if($datetime1->format('%m') != 0)
      {
         echo $datetime1->format('%m Month');
      }
      if($datetime1->format('%d') != 0)
      {
         echo $datetime1->format('%d Day');
      }
      if($datetime1->format('%h') != 0)
      {
         echo $datetime1->format('%h Hour');
      }
      if($datetime1->format('%i') != 0)
      {
         echo $datetime1->format('%i Min');
      }
      if($datetime1->format('%s') != 0)
      {
         echo $datetime1->format('%s Second');
      }

  ?>
Related