note 102271 modified in dateinterval.format by aharvey
| From: | aharvey@php.net | Date: | Wed, 20 Mar 2013 18:51:45 +0000 |
| Subject: | note 102271 modified in dateinterval.format by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-194147@lists.php.net to get a copy of this message | ||
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');
?>
--was--
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->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');
?>
http://php.net/manual/en/dateinterval.format.php