note 102813 deleted from dateinterval.format by danbrown

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: niallm90 at gmail dot com 

----

This is a modification and re-post of kuzb posts http://www.php.net/manual/en/dateinterval.format.php#102271. 

Fix: to_seconds function to include minutes.

Here is the complete post with modifications:

Quick class to allow you to input a time in any unit, and have it recalculate in to different denominations (for example, seconds to hours, minutes and seconds):

<?php
    class DateIntervalEnhanced extends DateInterval
    {

      /* Keep in mind that a year is seen in this class as 365 days, and a month is seen as 30 days.        
         It is not possible to calculate how many days are in a given year or month without a point of 
         reference in time.*/
      public function to_seconds()
      {
        return ($this->y * 365 * 24 * 60 * 60) +
               ($this->m * 30 * 24 * 60 * 60) +
               ($this->d * 24 * 60 * 60) +
               ($this->h * 60 * 60) +
               ($this->i * 60) +
               $this->s;
      }
     
      public function recalculate()
      {
        $seconds = $this->to_seconds();
        $this->y = floor($seconds/60/60/24/365);
        $seconds -= $this->y * 31536000;
        $this->m = floor($seconds/60/60/24/30);
        $seconds -= $this->m * 2592000;
        $this->d = floor($seconds/60/60/24);
        $seconds -= $this->d * 86400;
        $this->h = floor($seconds/60/60);
        $seconds -= $this->h * 3600;
        $this->i = floor($seconds/60);
        $seconds -= $this->i * 60;
        $this->s = $seconds;
      }
    }

    // Example usage
    $di = new DateIntervalEnhanced('PT3600S');
    $di->recalculate();
    // outputs 1:0:0 instead of 0:0:3600 now!
    echo $di->format('%H:%i:%s');
?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.