public
Created

TimeInterval class

  • Download Gist
gistfile1.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
<?php
/**
* Representation of a time interval, such as 1 year,
* or a more complex interval such as 1 month, 4 days and 6 hours.
* Provides methods for adding and substracting this interval
* to/from a given DateTime object or to/from a UNIX timestamp.
* Sample usage:
* $int = new TimeInterval(1, TimeInterval::YEAR); //1 year
* $int->addInterval(1, TimeInterval::MONTH); //allows creating more complex intervals (optional)
* $future = $int->addToDate(); //$future will be a DateTime object set to 1 year and 1 month from now
* $future = $int->addToDate(date_create('1955-11-05 20:00:00')); //$future will be a DateTime object set to 1956-12-05 20:00:00
* $intM = $int->toInterval(TimeInterval::MONTH);//converts this interval to months ($intM = 13)
*/
class TimeInterval
{
private $_intervals = array();
const YEAR = 0;
const MONTH = 1;
const WEEK = 2;
const DAY = 3;
const HOUR = 4;
const MINUTE = 5;
const SECOND = 6;
private static $conversionTable = array(
self::YEAR => array(
self::MONTH => 12,
),
self::MONTH => array(
self::WEEK => 4.34812,
),
self::WEEK => array(
self::DAY => 7,
),
self::DAY => array(
self::HOUR => 24,
),
self::HOUR => array(
self::MINUTE => 60,
),
self::MINUTE => array(
self::SECOND => 60,
),
);
/**
* Constructor
* Creates a TimeInterval instance using the provided time interval.
* @see addInterval()
* @param int $interval number of units
* @param int $unit time unit (must be one of TimeInterval class constants)
*/
public function __construct($interval, $unit = self::SECOND)
{
$this->addInterval($interval, $unit);
}
/**
* Adds the specified time interval to this instance.
* Use this method to specify a complex interval.
* @param int $interval number of units
* @param int $unit time unit (must be one of TimeInterval class constants)
*/
public function addInterval($interval, $unit = self::SECOND)
{
if (!array_key_exists($unit, $this->_getUnits()))
$unit = self::SECOND;
if (!isset($this->_intervals[$unit]))
$this->_intervals[$unit] = 0;
$this->_intervals[$unit] += $interval;
ksort($this->_intervals);
}
/**
* Adds this time interval to the provided DateTime object.
* If no DateTime object is supplied, it creates one from current time.
* When adding months, there is a risk of the result "overflowing".
* Eg: when adding 1 month to 2013-01-31, result is 2013-03-03.
* To prevent this overflow, set $preventMonthOverflow to true.
* In that case, return date would be 2013-02-28
* @param DateTime $date
* @param bool $preventMonthOverflow
* @return DateTime
*/
public function addToDate(DateTime $date = null, $preventMonthOverflow = false)
{
if ($date === null)
$date = date_create();
else
$date = clone $date;
foreach ($this->_intervals as $unit => $interval)
{
$newDate = clone $date;
$newDate->add(new DateInterval($this->_getIntervalSpecification($interval, $unit)));
if ($preventMonthOverflow and $unit == self::MONTH)
while ($this->_monthDiff($newDate, $date) > $interval)
$newDate->modify("-1 day");
$date = $newDate;
}
return $date;
}
/**
* Adds this time interval to the provided UNIX timestamp.
* If no timestamp is supplied, it creates one from current time.
* @param int $time
* @return int
*/
public function addToTime($time = null)
{
if ($time === null)
$time = time();
return $time + $this->toSeconds();
}
/**
* Substracts this time interval from the provided DateTime object.
* If no DateTime object is supplied, it creates one from current time.
* When substracting months, there is a risk of the result "overflowing".
* Eg: when substracting 1 month from 2013-03-31, result is 2013-03-03.
* To prevent this overflow, set $preventMonthOverflow to true.
* In that case, return date would be 2013-02-28
* @param DateTime $date
* @param bool $preventMonthOverflow
* @return DateTime
*/
public function substractFromDate(DateTime $date = null, $preventMonthOverflow = false)
{
if ($date === null)
$date = date_create();
else
$date = clone $date;
foreach ($this->_intervals as $unit => $interval)
{
$newDate = clone $date;
$newDate->sub(new DateInterval($this->_getIntervalSpecification($interval, $unit)));
if ($preventMonthOverflow and $unit == self::MONTH)
while ($this->_monthDiff($newDate, $date) < $interval)
$newDate->modify("-1 day");
$date = $newDate;
}
return $date;
}
/**
* Substracts this time interval from the provided UNIX timestamp.
* If no timestamp is supplied, it creates one from current time.
* @param int $time
* @return int
*/
public function substractFromTime($time = null)
{
if ($time === null)
$time = time();
return $time - $this->toSeconds();
}
/**
* Converts this time interval to seconds.
* @return int
*/
public function toSeconds()
{
return $this->toInterval(self::SECOND);
}
/**
* Converts one time interval to another
* @param int $i1 (one of TimeInterval constants)
* @param int $i2 (one of TimeInterval constants)
* @return number
*/
public static function convert($i1, $i2)
{
if ($i1 < self::YEAR or $i2 < self::YEAR or $i1 > self::SECOND or $i2 > self::SECOND)
return 0;
if ($i1 == $i2)
return 1;
if ($i1 < $i2) //eg day to hour
{
$to = key(self::$conversionTable[$i1]);
$factor = current(self::$conversionTable[$i1]);
if ($to == $i2)
return $factor;
else
return $factor * self::convert($to, $i2);
}
else //eg hour to day
{
foreach (self::$conversionTable as $to => $conversions)
{
if (!array_key_exists($i1, $conversions))
continue;
$factor = 1 / current($conversions);
if ($to == $i2)
return $factor;
else
return $factor * self::convert($to, $i2);
}
}
}
/**
* Converts this interval to another.
* @param int $toInterval interval to convert to (one of TimeInterval constants)
* @return number
*/
public function toInterval($toInterval)
{
$v = 0;
foreach ($this->_intervals as $fromInterval => $unit)
$v += $unit * self::convert($fromInterval, $toInterval);
return $v;
}
/**
* Magic method for converting to string
* @return string
*/
public function __toString()
{
return $this->asString();
}
/**
* Provides a string representation of this time interval
* (eg "1 year, 1 month")
* @param $singularMode - if true, returns in the form "3-month",
* otherwise uses form "3 months"
* @return string
*/
public function asString($singularMode = false)
{
$s = array();
$units = $this->_getUnits();
foreach ($this->_intervals as $unit => $interval)
{
if ($singularMode)
$s[] = $interval . '-' . ucfirst(strtolower($units[$unit]));
else
$s[] = $interval . ' ' . ucfirst(strtolower($units[$unit])) . ($interval > 1 ? 's' : '');
}
return join(', ', $s);
}
/**
* Returns this interval as a string suitable for use in SQL queries.
* Doesn't work with complex intervals.
* @throws TimeIntervalException if this is a complex interval
* @return string
*/
public function toSqlInterval()
{
if (count($this->_intervals) > 1)
throw new TimeIntervalException("Cannot convert complex intervals to SQL");
$units = $this->_getUnits();
$unit = key($this->_intervals);
$interval = current($this->_intervals);
return $interval . ' ' . $units[$unit];
}
private function _getUnits()
{
$r = new ReflectionClass(__CLASS__);
return array_flip($r->getConstants());
}
private function _monthDiff(DateTime $date1, DateTime $date2)
{
$ts1 = $date1->getTimestamp();
$ts2 = $date2->getTimestamp();
if ($ts1 == $ts2)
return 0;
elseif ($ts1 > $ts2)
{
$dateHi = $date1;
$dateLo = $date2;
}
else
{
$dateHi = $date2;
$dateLo = $date1;
}
return $dateHi->format('n') + 12 * ($dateHi->format('Y') - $dateLo->format('Y')) - $dateLo->format('n');
}
private function _getIntervalSpecification($interval, $unit)
{
$ps = $unit >= self::HOUR ? 'PT' : 'P';
$units = $this->_getUnits();
return sprintf("%s%d%s", $ps, $interval, substr($units[$unit], 0, 1));
}
/**
* Helper method. Does the same as constructor.
* @param int $interval
* @param int $unit
* @return TimeInterval
*/
public static function create($interval, $unit)
{
return new TimeInterval($interval, $unit);
}
/**
* Creates an instance of TimeInterval from a date range
* @param DateTime $date1
* @param DateTime $date2
* @return TimeInterval
*/
public static function fromDateRange(DateTime $date1, DateTime $date2)
{
$seconds = abs($date1->getTimestamp() - $date2->getTimestamp());
return new TimeInterval($seconds, self::SECOND);
}
/**
* Multiplies this interval by the provided factor.
* Eg interval of 1 month and 3 days multiplied by
* 3 will become 3 months and 9 days.
* @param int $factor
* @return TimeInterval
*/
public function multiply($factor)
{
foreach ($this->_intervals as $interval => &$unit)
$unit *= $factor;
return $this;
}
/**
* Merges this TimeInterval with the one provided
* in argument. Merging simply means that two intervals
* are added together (eg 2 months + 1 month and 1 day = 3 months and 1 day)
* @param TimeInterval $timeInterval
* @return TimeInterval
*/
public function mergeWith(TimeInterval $timeInterval)
{
foreach ($timeInterval->_intervals as $unit => $interval)
$this->addInterval($interval, $unit);
return $this;
}
}
 
class TimeIntervalException extends Exception {}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.