Skip to content

Instantly share code, notes, and snippets.

@raphaeltraviss
Created April 16, 2015 15:51
Show Gist options
  • Save raphaeltraviss/d06fc8881784fb9c9055 to your computer and use it in GitHub Desktop.
Save raphaeltraviss/d06fc8881784fb9c9055 to your computer and use it in GitHub Desktop.
PHP Date interval class that can recalculate values for date components.

PHP Date Interval Enhanced

What does this do?

It recalculates all of the date components after you modify them. For example, if you do $test = new DateIntervalEnhanced('PT6000S');, you can then do $test->recalculate() and process the seconds into hours, minutes, and seconds.

Options

In the example above, let's say you don't want any hours: you just want minutes and seconds. Do $test->recalculate('m'); and the conversion will leave all of the remaining hours, days, months, etc. as minutes.

<?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;
}
/**
* Recalculates the interval into date components.
*
* @param: $date_component (string) a PHP date component string that the
* conversion will stop at. For example, if there are two days' worth of
* time, and you input 'h', then the conversion will leave the time as
* hours. Conversions are done from year to second.
**/
public function recalculate($date_component = NULL) {
$conversions = array(
'y' => 31536000,
'm' => 2592000,
'd' => 86400,
'h' => 3600,
'i' => 60,
's' => 1,
);
// Remove conversions leading up to the date component, if given.
if (!empty($date_component)) {
foreach ($conversions as $conversion_component => $conversion_factor) {
if ($date_component == $conversion_component) {
break;
}
else {
unset($conversions[$conversion_component]);
}
}
// Clean up variables.
unset($conversion_component);
unset($conversion_factor);
}
// Process the conversions.
$seconds = $this->to_seconds();
foreach ($conversions as $conversion_component => $conversion_factor) {
$conversion = floor($seconds / $conversion_factor);
$this->$conversion_component = $conversion;
$seconds -= ($conversion * $conversion_factor);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment