2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
7 * Generic time span handling class for PEAR
13 * Copyright (c) 1997-2005 Leandro Lucarella, Pierre-Alain Joye
14 * All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted under the terms of the BSD License.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
32 * @category Date and Time
34 * @author Leandro Lucarella <llucax@php.net>
35 * @author Pierre-Alain Joye <pajoye@php.net>
36 * @copyright 1997-2006 Leandro Lucarella, Pierre-Alain Joye
37 * @license http://www.opensource.org/licenses/bsd-license.php
39 * @version CVS: $Id: Span.php,v 1.9 2006/11/21 17:38:15 firman Exp $
40 * @link http://pear.php.net/package/Date
41 * @since File available since Release 1.4
50 require_once 'Date.php';
53 * Get the Date_Calc class
55 require_once 'Date/Calc.php';
61 * Non Numeric Separated Values (NNSV) Input Format.
63 * Input format guessed from something like this:
64 * days<sep>hours<sep>minutes<sep>seconds
65 * Where <sep> is any quantity of non numeric chars. If no values are
66 * given, time span is set to zero, if one value is given, it's used for
67 * hours, if two values are given it's used for hours and minutes and if
68 * three values are given, it's used for hours, minutes and seconds.<br>
70 * '' -> 0, 0, 0, 0 (days, hours, minutes, seconds)<br>
72 * '12.30' -> 0, 12, 30, 0<br>
73 * '12:30:18' -> 0, 12, 30, 18<br>
74 * '3-12-30-18' -> 3, 12, 30, 18<br>
75 * '3 days, 12-30-18' -> 3, 12, 30, 18<br>
76 * '12:30 with 18 secs' -> 0, 12, 30, 18<br>
80 define('DATE_SPAN_INPUT_FORMAT_NNSV', 1);
83 // {{{ Global Variables
86 * Default time format when converting to a string.
90 $GLOBALS['_DATE_SPAN_FORMAT'] = '%C';
93 * Default time format when converting from a string.
97 $GLOBALS['_DATE_SPAN_INPUT_FORMAT'] = DATE_SPAN_INPUT_FORMAT_NNSV
;
100 // {{{ Class: Date_Span
103 * Generic time span handling class for PEAR
105 * @author Leandro Lucarella <llucax@php.net>
106 * @author Pierre-Alain Joye <pajoye@php.net>
107 * @copyright 1997-2006 Leandro Lucarella, Pierre-Alain Joye
108 * @license http://www.opensource.org/licenses/bsd-license.php
110 * @version Release: 1.4.7
111 * @link http://pear.php.net/package/Date
112 * @since Class available since Release 1.4
144 * Creates the time span object calling the set() method.
146 * @param mixed $time Time span expression.
147 * @param mixed $format Format string to set it from a string or the
148 * second date set it from a date diff.
153 function Date_Span($time = 0, $format = null)
155 $this->set($time, $format);
162 * Set the time span to a new value in a 'smart' way.
164 * Sets the time span depending on the argument types, calling
165 * to the appropriate setFromXxx() method.
167 * @param mixed $time Time span expression.
168 * @param mixed $format Format string to set it from a string or the
169 * second date set it from a date diff.
171 * @return bool true on success.
173 * @see setFromObject()
174 * @see setFromArray()
175 * @see setFromString()
176 * @see setFromSeconds()
177 * @see setFromDateDiff()
180 function set($time = 0, $format = null)
182 if (is_a($time, 'date_span')) {
183 return $this->copy($time);
184 } elseif (is_a($time, 'date') and is_a($format, 'date')) {
185 return $this->setFromDateDiff($time, $format);
186 } elseif (is_array($time)) {
187 return $this->setFromArray($time);
188 } elseif (is_string($time)) {
189 return $this->setFromString($time, $format);
190 } elseif (is_int($time)) {
191 return $this->setFromSeconds($time);
193 return $this->setFromSeconds(0);
198 // {{{ setFromArray()
201 * Set the time span from an array.
203 * Set the time span from an array. Any value can be a float (but it
204 * has no sense in seconds), for example array(23.5, 20, 0) is
205 * interpreted as 23 hours, .5*60 + 20 = 50 minutes and 0 seconds.
207 * @param array $time Items are counted from right to left. First
208 * item is for seconds, second for minutes, third
209 * for hours and fourth for days. If there are
210 * less items than 4, zero (0) is assumed for the
213 * @return bool True on success.
217 function setFromArray($time)
219 if (!is_array($time)) {
222 $tmp1 = new Date_Span
;
223 if (!$tmp1->setFromSeconds(@array_pop
($time))) {
226 $tmp2 = new Date_Span
;
227 if (!$tmp2->setFromMinutes(@array_pop
($time))) {
231 if (!$tmp2->setFromHours(@array_pop
($time))) {
235 if (!$tmp2->setFromDays(@array_pop
($time))) {
239 return $this->copy($tmp1);
243 // {{{ setFromString()
246 * Set the time span from a string based on an input format.
248 * Set the time span from a string based on an input format. This is
249 * some like a mix of format() method and sscanf() PHP function. The
250 * error checking and validation of this function is very primitive,
251 * so you should be carefull when using it with unknown $time strings.
252 * With this method you are assigning day, hour, minute and second
253 * values, and the last values are used. This means that if you use
254 * something like setFromString('10, 20', '%H, %h') your time span
255 * would be 20 hours long. Allways remember that this method set
256 * <b>all</b> the values, so if you had a $time span 30 minutes long
257 * and you make $time->setFromString('20 hours', '%H hours'), $time
258 * span would be 20 hours long (and not 20 hours and 30 minutes).
259 * Input format options:<br>
260 * <code>%C</code> Days with time, same as "%D, %H:%M:%S".<br>
261 * <code>%d</code> Total days as a float number
262 * (2 days, 12 hours = 2.5 days).<br>
263 * <code>%D</code> Days as a decimal number.<br>
264 * <code>%e</code> Total hours as a float number
265 * (1 day, 2 hours, 30 minutes = 26.5 hours).<br>
266 * <code>%f</code> Total minutes as a float number
267 * (2 minutes, 30 seconds = 2.5 minutes).<br>
268 * <code>%g</code> Total seconds as a decimal number
269 * (2 minutes, 30 seconds = 90 seconds).<br>
270 * <code>%h</code> Hours as decimal number.<br>
271 * <code>%H</code> Hours as decimal number limited to 2 digits.<br>
272 * <code>%m</code> Minutes as a decimal number.<br>
273 * <code>%M</code> Minutes as a decimal number limited to 2 digits.<br>
274 * <code>%n</code> Newline character (\n).<br>
275 * <code>%p</code> Either 'am' or 'pm' depending on the time. If 'pm'
276 * is detected it adds 12 hours to the resulting time
277 * span (without any checks). This is case
279 * <code>%r</code> Time in am/pm notation, same as "%H:%M:%S %p".<br>
280 * <code>%R</code> Time in 24-hour notation, same as "%H:%M".<br>
281 * <code>%s</code> Seconds as a decimal number.<br>
282 * <code>%S</code> Seconds as a decimal number limited to 2 digits.<br>
283 * <code>%t</code> Tab character (\t).<br>
284 * <code>%T</code> Current time equivalent, same as "%H:%M:%S".<br>
285 * <code>%%</code> Literal '%'.<br>
287 * @param string $time String from where to get the time span
289 * @param string $format Format string.
291 * @return bool True on success.
295 function setFromString($time, $format = null)
297 if (is_null($format)) {
298 $format = $GLOBALS['_DATE_SPAN_INPUT_FORMAT'];
300 // If format is a string, it parses the string format.
301 if (is_string($format)) {
305 $day = $hour = $minute = $second = 0;
306 for ($i = 0; $i < strlen($format); $i++
) {
309 $nextchar = $format{++
$i};
312 $str .= '%d, %d:%d:%d';
314 $vars, 'day', 'hour', 'minute', 'second');
317 $str .= '%d, %2d:%2d:%2d';
319 $vars, 'day', 'hour', 'minute', 'second');
323 array_push($vars, 'day');
327 array_push($vars, 'day');
331 array_push($vars, 'hour');
335 array_push($vars, 'minute');
339 array_push($vars, 'second');
343 array_push($vars, 'hour');
347 array_push($vars, 'hour');
351 array_push($vars, 'minute');
355 array_push($vars, 'minute');
362 array_push($vars, 'pm');
365 $str .= '%2d:%2d:%2d %2s';
367 $vars, 'hour', 'minute', 'second', 'pm');
371 array_push($vars, 'hour', 'minute');
375 array_push($vars, 'second');
379 array_push($vars, 'second');
385 $str .= '%2d:%2d:%2d';
386 array_push($vars, 'hour', 'minute', 'second');
392 $str .= $char . $nextchar;
398 $vals = sscanf($time, $str);
399 foreach ($vals as $i => $val) {
405 if (strcasecmp($pm, 'pm') == 0) {
407 } elseif (strcasecmp($pm, 'am') != 0) {
410 $this->setFromArray(array($day, $hour, $minute, $second));
411 // If format is a integer, it uses a predefined format
413 } elseif (is_integer($format)) {
415 case DATE_SPAN_INPUT_FORMAT_NNSV
:
416 $time = preg_split('/\D+/', $time);
417 switch (count($time)) {
419 return $this->setFromArray(
422 return $this->setFromArray(
423 array(0, $time[0], 0, 0));
425 return $this->setFromArray(
426 array(0, $time[0], $time[1], 0));
428 return $this->setFromArray(
429 array(0, $time[0], $time[1], $time[2]));
431 return $this->setFromArray($time);
440 // {{{ setFromSeconds()
443 * Set the time span from a total number of seconds.
445 * @param int $seconds Total number of seconds.
447 * @return bool True on success.
451 function setFromSeconds($seconds)
456 $sec = intval($seconds);
457 $min = floor($sec / 60);
458 $hour = floor($min / 60);
459 $day = intval(floor($hour / 24));
460 $this->second
= $sec %
60;
461 $this->minute
= $min %
60;
462 $this->hour
= $hour %
24;
468 // {{{ setFromMinutes()
471 * Set the time span from a total number of minutes.
473 * @param float $minutes Total number of minutes.
475 * @return bool True on success.
479 function setFromMinutes($minutes)
481 return $this->setFromSeconds(round($minutes * 60));
485 // {{{ setFromHours()
488 * Set the time span from a total number of hours.
490 * @param float $hours Total number of hours.
492 * @return bool True on success.
496 function setFromHours($hours)
498 return $this->setFromSeconds(round($hours * 3600));
505 * Set the time span from a total number of days.
507 * @param float $days Total number of days.
509 * @return bool True on success.
513 function setFromDays($days)
515 return $this->setFromSeconds(round($days * 86400));
519 // {{{ setFromDateDiff()
522 * Set the span from the elapsed time between two dates.
524 * Set the span from the elapsed time between two dates. The time span
525 * is allways positive, so the date's order is not important.
527 * @param object Date $date1 First Date.
528 * @param object Date $date2 Second Date.
530 * @return bool True on success.
534 function setFromDateDiff($date1, $date2)
536 if (!is_a($date1, 'date') or !is_a($date2, 'date')) {
541 if ($date1->after($date2)) {
542 list($date1, $date2) = array($date2, $date1);
544 $days = Date_Calc
::dateDiff(
545 $date1->getDay(), $date1->getMonth(), $date1->getYear(),
546 $date2->getDay(), $date2->getMonth(), $date2->getYear()
548 $hours = $date2->getHour() - $date1->getHour();
549 $mins = $date2->getMinute() - $date1->getMinute();
550 $secs = $date2->getSecond() - $date1->getSecond();
551 $this->setFromSeconds(
552 $days * 86400 +
$hours * 3600 +
$mins * 60 +
$secs
561 * Set the time span from another time object.
563 * @param object Date_Span $time Source time span object.
565 * @return bool True on success.
571 if (is_a($time, 'date_span')) {
572 $this->second
= $time->second
;
573 $this->minute
= $time->minute
;
574 $this->hour
= $time->hour
;
575 $this->day
= $time->day
;
586 * Time span pretty printing (similar to Date::format()).
588 * Formats the time span in the given format, similar to
589 * strftime() and Date::format().<br>
591 * Formatting options:<br>
592 * <code>%C</code> Days with time, same as "%D, %H:%M:%S".<br>
593 * <code>%d</code> Total days as a float number
594 * (2 days, 12 hours = 2.5 days).<br>
595 * <code>%D</code> Days as a decimal number.<br>
596 * <code>%e</code> Total hours as a float number
597 * (1 day, 2 hours, 30 minutes = 26.5 hours).<br>
598 * <code>%E</code> Total hours as a decimal number
599 * (1 day, 2 hours, 40 minutes = 26 hours).<br>
600 * <code>%f</code> Total minutes as a float number
601 * (2 minutes, 30 seconds = 2.5 minutes).<br>
602 * <code>%F</code> Total minutes as a decimal number
603 * (1 hour, 2 minutes, 40 seconds = 62 minutes).<br>
604 * <code>%g</code> Total seconds as a decimal number
605 * (2 minutes, 30 seconds = 90 seconds).<br>
606 * <code>%h</code> Hours as decimal number (0 to 23).<br>
607 * <code>%H</code> Hours as decimal number (00 to 23).<br>
608 * <code>%i</code> Hours as decimal number on 12-hour clock
610 * <code>%I</code> Hours as decimal number on 12-hour clock
612 * <code>%m</code> Minutes as a decimal number (0 to 59).<br>
613 * <code>%M</code> Minutes as a decimal number (00 to 59).<br>
614 * <code>%n</code> Newline character (\n).<br>
615 * <code>%p</code> Either 'am' or 'pm' depending on the time.<br>
616 * <code>%P</code> Either 'AM' or 'PM' depending on the time.<br>
617 * <code>%r</code> Time in am/pm notation, same as "%I:%M:%S %p".<br>
618 * <code>%R</code> Time in 24-hour notation, same as "%H:%M".<br>
619 * <code>%s</code> Seconds as a decimal number (0 to 59).<br>
620 * <code>%S</code> Seconds as a decimal number (00 to 59).<br>
621 * <code>%t</code> Tab character (\t).<br>
622 * <code>%T</code> Current time equivalent, same as "%H:%M:%S".<br>
623 * <code>%%</code> Literal '%'.<br>
625 * @param string $format The format string for returned time span.
627 * @return string The time span in specified format.
631 function format($format = null)
633 if (is_null($format)) {
634 $format = $GLOBALS['_DATE_SPAN_FORMAT'];
637 for ($i = 0; $i < strlen($format); $i++
) {
640 $nextchar = $format{++
$i};
644 '%d, %02d:%02d:%02d',
652 $output .= $this->toDays();
655 $output .= $this->day
;
658 $output .= $this->toHours();
661 $output .= floor($this->toHours());
664 $output .= $this->toMinutes();
667 $output .= floor($this->toMinutes());
670 $output .= $this->toSeconds();
673 $output .= $this->hour
;
676 $output .= sprintf('%02d', $this->hour
);
680 ($this->hour +
1) > 12 ?
683 $output .= ($hour == 0) ?
12 : $hour;
687 ($this->hour +
1) > 12 ?
690 $output .= sprintf('%02d', $hour==0 ?
12 : $hour);
693 $output .= $this->minute
;
696 $output .= sprintf('%02d',$this->minute
);
702 $output .= $this->hour
>= 12 ?
'pm' : 'am';
705 $output .= $this->hour
>= 12 ?
'PM' : 'AM';
709 ($this->hour +
1) > 12 ?
714 $hour==0 ?
12 : $hour,
717 $this->hour
>= 12 ?
'pm' : 'am'
722 '%02d:%02d', $this->hour
, $this->minute
726 $output .= $this->second
;
729 $output .= sprintf('%02d', $this->second
);
737 $this->hour
, $this->minute
, $this->second
744 $output .= $char . $nextchar;
757 * Convert time span to seconds.
759 * @return int Time span as an integer number of seconds.
765 return $this->day
* 86400 +
$this->hour
* 3600 +
766 $this->minute
* 60 +
$this->second
;
773 * Convert time span to minutes.
775 * @return float Time span as a decimal number of minutes.
781 return $this->day
* 1440 +
$this->hour
* 60 +
$this->minute +
789 * Convert time span to hours.
791 * @return float Time span as a decimal number of hours.
797 return $this->day
* 24 +
$this->hour +
$this->minute
/ 60 +
798 $this->second
/ 3600;
805 * Convert time span to days.
807 * @return float Time span as a decimal number of days.
813 return $this->day +
$this->hour
/ 24 +
$this->minute
/ 1440 +
814 $this->second
/ 86400;
823 * @param object Date_Span $time Time span to add.
829 return $this->setFromSeconds(
830 $this->toSeconds() +
$time->toSeconds()
838 * Subtracts a time span.
840 * Subtracts a time span. If the time span to subtract is larger
841 * than the original, the result is zero (there's no sense in
842 * negative time spans).
844 * @param object Date_Span $time Time span to subtract.
848 function subtract($time)
850 $sub = $this->toSeconds() - $time->toSeconds();
852 $this->setFromSeconds(0);
854 $this->setFromSeconds($sub);
862 * Tells if time span is equal to $time.
864 * @param object Date_Span $time Time span to compare to.
866 * @return bool True if the time spans are equal.
870 function equal($time)
872 return $this->toSeconds() == $time->toSeconds();
876 // {{{ greaterEqual()
879 * Tells if this time span is greater or equal than $time.
881 * @param object Date_Span $time Time span to compare to.
883 * @return bool True if this time span is greater or equal than $time.
887 function greaterEqual($time)
889 return $this->toSeconds() >= $time->toSeconds();
896 * Tells if this time span is lower or equal than $time.
898 * @param object Date_Span $time Time span to compare to.
900 * @return bool True if this time span is lower or equal than $time.
904 function lowerEqual($time)
906 return $this->toSeconds() <= $time->toSeconds();
913 * Tells if this time span is greater than $time.
915 * @param object Date_Span $time Time span to compare to.
917 * @return bool True if this time span is greater than $time.
921 function greater($time)
923 return $this->toSeconds() > $time->toSeconds();
930 * Tells if this time span is lower than $time.
932 * @param object Date_Span $time Time span to compare to.
934 * @return bool True if this time span is lower than $time.
938 function lower($time)
940 return $this->toSeconds() < $time->toSeconds();
947 * Compares two time spans.
949 * Compares two time spans. Suitable for use in sorting functions.
951 * @param object Date_Span $time1 The first time span.
952 * @param object Date_Span $time2 The second time span.
954 * @return int 0 if the time spans are equal, -1 if time1 is lower
955 * than time2, 1 if time1 is greater than time2.
960 function compare($time1, $time2)
962 if ($time1->equal($time2)) {
964 } elseif ($time1->lower($time2)) {
975 * Tells if the time span is empty (zero length).
977 * @return bool True is it's empty.
981 return !$this->day
&& !$this->hour
&& !$this->minute
&& !$this->second
;
985 // {{{ setDefaultInputFormat()
988 * Set the default input format.
990 * @param mixed $format New default input format.
992 * @return mixed Previous default input format.
996 function setDefaultInputFormat($format)
998 $old = $GLOBALS['_DATE_SPAN_INPUT_FORMAT'];
999 $GLOBALS['_DATE_SPAN_INPUT_FORMAT'] = $format;
1004 // {{{ getDefaultInputFormat()
1007 * Get the default input format.
1009 * @return mixed Default input format.
1013 function getDefaultInputFormat()
1015 return $GLOBALS['_DATE_SPAN_INPUT_FORMAT'];
1019 // {{{ setDefaultFormat()
1022 * Set the default format.
1024 * @param mixed $format New default format.
1026 * @return mixed Previous default format.
1030 function setDefaultFormat($format)
1032 $old = $GLOBALS['_DATE_SPAN_FORMAT'];
1033 $GLOBALS['_DATE_SPAN_FORMAT'] = $format;
1038 // {{{ getDefaultFormat()
1041 * Get the default format.
1043 * @return mixed Default format.
1047 function getDefaultFormat()
1049 return $GLOBALS['_DATE_SPAN_FORMAT'];
1056 * Returns a copy of the object (workarround for PHP5 forward compatibility).
1058 * @return object Date_Span Copy of the object.
1060 function __clone() {
1061 $c = get_class($this);
1063 $s->day
= $this->day
;
1064 $s->hour
= $this->hour
;
1065 $s->minute
= $this->minute
;
1066 $s->second
= $this->second
;
1080 * c-hanging-comment-ender-p: nil