time.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: time.php 8252 2009-07-23 20:51:24Z DarkAngelBGE $ */
00003 /**
00004  * Time Helper class file.
00005  *
00006  * PHP versions 4 and 5
00007  *
00008  * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
00009  * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00010  *
00011  * Licensed under The MIT License
00012  * Redistributions of files must retain the above copyright notice.
00013  *
00014  * @filesource
00015  * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00016  * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
00017  * @package       cake
00018  * @subpackage    cake.cake.libs.view.helpers
00019  * @since         CakePHP(tm) v 0.10.0.1076
00020  * @version       $Revision: 8252 $
00021  * @modifiedby    $LastChangedBy: DarkAngelBGE $
00022  * @lastmodified  $Date: 2009-07-23 16:51:24 -0400 (Thu, 23 Jul 2009) $
00023  * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
00024  */
00025 /**
00026  * Time Helper class for easy use of time data.
00027  *
00028  * Manipulation of time data.
00029  *
00030  * @package       cake
00031  * @subpackage    cake.cake.libs.view.helpers
00032  */
00033 class TimeHelper extends AppHelper {
00034 /**
00035  * Converts given time (in server's time zone) to user's local time, given his/her offset from GMT.
00036  *
00037  * @param string $serverTime UNIX timestamp
00038  * @param int $userOffset User's offset from GMT (in hours)
00039  * @return string UNIX timestamp
00040  */
00041     function convert($serverTime, $userOffset) {
00042         $serverOffset = $this->serverOffset();
00043         $gmtTime = $serverTime - $serverOffset;
00044         $userTime = $gmtTime + $userOffset * (60*60);
00045         return $userTime;
00046     }
00047 /**
00048  * Returns server's offset from GMT in seconds.
00049  *
00050  * @return int Offset
00051  */
00052     function serverOffset() {
00053         return date('Z', time());
00054     }
00055 /**
00056  * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
00057  *
00058  * @param string $dateString Datetime string
00059  * @param int $userOffset User's offset from GMT (in hours)
00060  * @return string Parsed timestamp
00061  */
00062     function fromString($dateString, $userOffset = null) {
00063         if (empty($dateString)) {
00064             return false;
00065         }
00066         if (is_integer($dateString) || is_numeric($dateString)) {
00067             $date = intval($dateString);
00068         } else {
00069             $date = strtotime($dateString);
00070         }
00071         if ($userOffset !== null) {
00072             return $this->convert($date, $userOffset);
00073         }
00074         return $date;
00075     }
00076 /**
00077  * Returns a nicely formatted date string for given Datetime string.
00078  *
00079  * @param string $dateString Datetime string or Unix timestamp
00080  * @param int $userOffset User's offset from GMT (in hours)
00081  * @return string Formatted date string
00082  */
00083     function nice($dateString = null, $userOffset = null) {
00084         if ($dateString != null) {
00085             $date = $this->fromString($dateString, $userOffset);
00086         } else {
00087             $date = time();
00088         }
00089 
00090         $ret = date("D, M jS Y, H:i", $date);
00091         return $this->output($ret);
00092     }
00093 /**
00094  * Returns a formatted descriptive date string for given datetime string.
00095  *
00096  * If the given date is today, the returned string could be "Today, 16:54".
00097  * If the given date was yesterday, the returned string could be "Yesterday, 16:54".
00098  * If $dateString's year is the current year, the returned string does not
00099  * include mention of the year.
00100  *
00101  * @param string $dateString Datetime string or Unix timestamp
00102  * @param int $userOffset User's offset from GMT (in hours)
00103  * @return string Described, relative date string
00104  */
00105     function niceShort($dateString = null, $userOffset = null) {
00106         $date = $dateString ? $this->fromString($dateString, $userOffset) : time();
00107 
00108         $y = $this->isThisYear($date) ? '' : ' Y';
00109 
00110         if ($this->isToday($date)) {
00111             $ret = sprintf(__('Today, %s',true), date("H:i", $date));
00112         } elseif ($this->wasYesterday($date)) {
00113             $ret = sprintf(__('Yesterday, %s',true), date("H:i", $date));
00114         } else {
00115             $ret = date("M jS{$y}, H:i", $date);
00116         }
00117 
00118         return $this->output($ret);
00119     }
00120 /**
00121  * Returns a partial SQL string to search for all records between two dates.
00122  *
00123  * @param string $dateString Datetime string or Unix timestamp
00124  * @param string $end Datetime string or Unix timestamp
00125  * @param string $fieldName Name of database field to compare with
00126  * @param int $userOffset User's offset from GMT (in hours)
00127  * @return string Partial SQL string.
00128  */
00129     function daysAsSql($begin, $end, $fieldName, $userOffset = null) {
00130         $begin = $this->fromString($begin, $userOffset);
00131         $end = $this->fromString($end, $userOffset);
00132         $begin = date('Y-m-d', $begin) . ' 00:00:00';
00133         $end = date('Y-m-d', $end) . ' 23:59:59';
00134 
00135         $ret  ="($fieldName >= '$begin') AND ($fieldName <= '$end')";
00136         return $this->output($ret);
00137     }
00138 /**
00139  * Returns a partial SQL string to search for all records between two times
00140  * occurring on the same day.
00141  *
00142  * @param string $dateString Datetime string or Unix timestamp
00143  * @param string $fieldName Name of database field to compare with
00144  * @param int $userOffset User's offset from GMT (in hours)
00145  * @return string Partial SQL string.
00146  */
00147     function dayAsSql($dateString, $fieldName, $userOffset = null) {
00148         $date = $this->fromString($dateString, $userOffset);
00149         $ret = $this->daysAsSql($dateString, $dateString, $fieldName);
00150         return $this->output($ret);
00151     }
00152 /**
00153  * Returns true if given datetime string is today.
00154  *
00155  * @param string $dateString Datetime string or Unix timestamp
00156  * @param int $userOffset User's offset from GMT (in hours)
00157  * @return boolean True if datetime string is today
00158  */
00159     function isToday($dateString, $userOffset = null) {
00160         $date = $this->fromString($dateString, $userOffset);
00161         return date('Y-m-d', $date) == date('Y-m-d', time());
00162     }
00163 /**
00164  * Returns true if given datetime string is within this week
00165  * @param string $dateString
00166  * @param int $userOffset User's offset from GMT (in hours)
00167  * @return boolean True if datetime string is within current week
00168  */
00169     function isThisWeek($dateString, $userOffset = null) {
00170         $date = $this->fromString($dateString, $userOffset);
00171         return date('W Y', $date) == date('W Y', time());
00172     }
00173 /**
00174  * Returns true if given datetime string is within this month
00175  * @param string $dateString
00176  * @param int $userOffset User's offset from GMT (in hours)
00177  * @return boolean True if datetime string is within current month
00178  */
00179     function isThisMonth($dateString, $userOffset = null) {
00180         $date = $this->fromString($dateString);
00181         return date('m Y',$date) == date('m Y', time());
00182     }
00183 /**
00184  * Returns true if given datetime string is within current year.
00185  *
00186  * @param string $dateString Datetime string or Unix timestamp
00187  * @return boolean True if datetime string is within current year
00188  */
00189     function isThisYear($dateString, $userOffset = null) {
00190         $date = $this->fromString($dateString, $userOffset);
00191         return  date('Y', $date) == date('Y', time());
00192     }
00193 /**
00194  * Returns true if given datetime string was yesterday.
00195  *
00196  * @param string $dateString Datetime string or Unix timestamp
00197  * @param int $userOffset User's offset from GMT (in hours)
00198  * @return boolean True if datetime string was yesterday
00199  */
00200     function wasYesterday($dateString, $userOffset = null) {
00201         $date = $this->fromString($dateString, $userOffset);
00202         return date('Y-m-d', $date) == date('Y-m-d', strtotime('yesterday'));
00203     }
00204 /**
00205  * Returns true if given datetime string is tomorrow.
00206  *
00207  * @param string $dateString Datetime string or Unix timestamp
00208  * @param int $userOffset User's offset from GMT (in hours)
00209  * @return boolean True if datetime string was yesterday
00210  */
00211     function isTomorrow($dateString, $userOffset = null) {
00212         $date = $this->fromString($dateString, $userOffset);
00213         return date('Y-m-d', $date) == date('Y-m-d', strtotime('tomorrow'));
00214     }
00215 /**
00216  * Returns the quart
00217  * @param string $dateString
00218  * @param boolean $range if true returns a range in Y-m-d format
00219  * @return boolean True if datetime string is within current week
00220  */
00221     function toQuarter($dateString, $range = false) {
00222         $time = $this->fromString($dateString);
00223         $date = ceil(date('m', $time) / 3);
00224 
00225         if ($range === true) {
00226             $range = 'Y-m-d';
00227         }
00228 
00229         if ($range !== false) {
00230             $year = date('Y', $time);
00231 
00232             switch ($date) {
00233                 case 1:
00234                     $date = array($year.'-01-01', $year.'-03-31');
00235                     break;
00236                 case 2:
00237                     $date = array($year.'-04-01', $year.'-06-30');
00238                     break;
00239                 case 3:
00240                     $date = array($year.'-07-01', $year.'-09-30');
00241                     break;
00242                 case 4:
00243                     $date = array($year.'-10-01', $year.'-12-31');
00244                     break;
00245             }
00246         }
00247         return $this->output($date);
00248     }
00249 /**
00250  * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime().
00251  *
00252  * @param string $dateString Datetime string to be represented as a Unix timestamp
00253  * @param int $userOffset User's offset from GMT (in hours)
00254  * @return integer Unix timestamp
00255  */
00256     function toUnix($dateString, $userOffset = null) {
00257         $ret = $this->fromString($dateString, $userOffset);
00258         return $this->output($ret);
00259     }
00260 /**
00261  * Returns a date formatted for Atom RSS feeds.
00262  *
00263  * @param string $dateString Datetime string or Unix timestamp
00264  * @param int $userOffset User's offset from GMT (in hours)
00265  * @return string Formatted date string
00266  */
00267     function toAtom($dateString, $userOffset = null) {
00268         $date = $this->fromString($dateString, $userOffset);
00269         $ret = date('Y-m-d\TH:i:s\Z', $date);
00270         return $this->output($ret);
00271     }
00272 /**
00273  * Formats date for RSS feeds
00274  *
00275  * @param string $dateString Datetime string or Unix timestamp
00276  * @param int $userOffset User's offset from GMT (in hours)
00277  * @return string Formatted date string
00278  */
00279     function toRSS($dateString, $userOffset = null) {
00280         $date = $this->fromString($dateString, $userOffset);
00281         $ret = date("r", $date);
00282         return $this->output($ret);
00283     }
00284 /**
00285  * Returns either a relative date or a formatted date depending
00286  * on the difference between the current time and given datetime.
00287  * $datetime should be in a <i>strtotime</i> - parsable format, like MySQL's datetime datatype.
00288  *
00289  * Options:
00290  *
00291  * - 'format' => a fall back format if the relative time is longer than the duration specified by end
00292  * - 'end' => The end of relative time telling
00293  * - 'userOffset' => Users offset from GMT (in hours)
00294  *
00295  * Relative dates look something like this:
00296  *  3 weeks, 4 days ago
00297  *  15 seconds ago
00298  * Formatted dates look like this:
00299  *  on 02/18/2004
00300  *
00301  * The returned string includes 'ago' or 'on' and assumes you'll properly add a word
00302  * like 'Posted ' before the function output.
00303  *
00304  * @param string $dateString Datetime string or Unix timestamp
00305  * @param array $options Default format if timestamp is used in $dateString
00306  * @return string Relative time string.
00307  */
00308     function timeAgoInWords($dateTime, $options = array()) {
00309         $userOffset = null;
00310         if (is_array($options) && isset($options['userOffset'])) {
00311             $userOffset = $options['userOffset'];
00312         }
00313         $now = time();
00314         if (!is_null($userOffset)) {
00315             $now =  $this->convert(time(), $userOffset);
00316         }
00317         $inSeconds = $this->fromString($dateTime, $userOffset);
00318         $backwards = ($inSeconds > $now);
00319 
00320         $format = 'j/n/y';
00321         $end = '+1 month';
00322 
00323         if (is_array($options)) {
00324             if (isset($options['format'])) {
00325                 $format = $options['format'];
00326                 unset($options['format']);
00327             }
00328             if (isset($options['end'])) {
00329                 $end = $options['end'];
00330                 unset($options['end']);
00331             }
00332         } else {
00333             $format = $options;
00334         }
00335 
00336         if ($backwards) {
00337             $futureTime = $inSeconds;
00338             $pastTime = $now;
00339         } else {
00340             $futureTime = $now;
00341             $pastTime = $inSeconds;
00342         }
00343         $diff = $futureTime - $pastTime;
00344 
00345         // If more than a week, then take into account the length of months
00346         if ($diff >= 604800) {
00347             $current = array();
00348             $date = array();
00349 
00350             list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime));
00351 
00352             list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime));
00353             $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0;
00354 
00355             if ($future['Y'] == $past['Y'] && $future['m'] == $past['m']) {
00356                 $months = 0;
00357                 $years = 0;
00358             } else {
00359                 if ($future['Y'] == $past['Y']) {
00360                     $months = $future['m'] - $past['m'];
00361                 } else {
00362                     $years = $future['Y'] - $past['Y'];
00363                     $months = $future['m'] + ((12 * $years) - $past['m']);
00364 
00365                     if ($months >= 12) {
00366                         $years = floor($months / 12);
00367                         $months = $months - ($years * 12);
00368                     }
00369 
00370                     if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] == 1) {
00371                         $years --;
00372                     }
00373                 }
00374             }
00375 
00376             if ($future['d'] >= $past['d']) {
00377                 $days = $future['d'] - $past['d'];
00378             } else {
00379                 $daysInPastMonth = date('t', $pastTime);
00380                 $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y']));
00381 
00382                 if (!$backwards) {
00383                     $days = ($daysInPastMonth - $past['d']) + $future['d'];
00384                 } else {
00385                     $days = ($daysInFutureMonth - $past['d']) + $future['d'];
00386                 }
00387 
00388                 if ($future['m'] != $past['m']) {
00389                     $months --;
00390                 }
00391             }
00392 
00393             if ($months == 0 && $years >= 1 && $diff < ($years * 31536000)) {
00394                 $months = 11;
00395                 $years --;
00396             }
00397 
00398             if ($months >= 12) {
00399                 $years = $years + 1;
00400                 $months = $months - 12;
00401             }
00402 
00403             if ($days >= 7) {
00404                 $weeks = floor($days / 7);
00405                 $days = $days - ($weeks * 7);
00406             }
00407         } else {
00408             $years = $months = $weeks = 0;
00409             $days = floor($diff / 86400);
00410 
00411             $diff = $diff - ($days * 86400);
00412 
00413             $hours = floor($diff / 3600);
00414             $diff = $diff - ($hours * 3600);
00415 
00416             $minutes = floor($diff / 60);
00417             $diff = $diff - ($minutes * 60);
00418             $seconds = $diff;
00419         }
00420         $relativeDate = '';
00421         $diff = $futureTime - $pastTime;
00422 
00423         if ($diff > abs($now - $this->fromString($end))) {
00424             $relativeDate = sprintf(__('on %s',true), date($format, $inSeconds));
00425         } else {
00426             if ($years > 0) {
00427                 // years and months and days
00428                 $relativeDate .= ($relativeDate ? ', ' : '') . $years . ' ' . __n('year', 'years', $years, true);
00429                 $relativeDate .= $months > 0 ? ($relativeDate ? ', ' : '') . $months . ' ' . __n('month', 'months', $months, true) : '';
00430                 $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks, true) : '';
00431                 $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true) : '';
00432             } elseif (abs($months) > 0) {
00433                 // months, weeks and days
00434                 $relativeDate .= ($relativeDate ? ', ' : '') . $months . ' ' . __n('month', 'months', $months, true);
00435                 $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks, true) : '';
00436                 $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true) : '';
00437             } elseif (abs($weeks) > 0) {
00438                 // weeks and days
00439                 $relativeDate .= ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks, true);
00440                 $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true) : '';
00441             } elseif (abs($days) > 0) {
00442                 // days and hours
00443                 $relativeDate .= ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true);
00444                 $relativeDate .= $hours > 0 ? ($relativeDate ? ', ' : '') . $hours . ' ' . __n('hour', 'hours', $hours, true) : '';
00445             } elseif (abs($hours) > 0) {
00446                 // hours and minutes
00447                 $relativeDate .= ($relativeDate ? ', ' : '') . $hours . ' ' . __n('hour', 'hours', $hours, true);
00448                 $relativeDate .= $minutes > 0 ? ($relativeDate ? ', ' : '') . $minutes . ' ' . __n('minute', 'minutes', $minutes, true) : '';
00449             } elseif (abs($minutes) > 0) {
00450                 // minutes only
00451                 $relativeDate .= ($relativeDate ? ', ' : '') . $minutes . ' ' . __n('minute', 'minutes', $minutes, true);
00452             } else {
00453                 // seconds only
00454                 $relativeDate .= ($relativeDate ? ', ' : '') . $seconds . ' ' . __n('second', 'seconds', $seconds, true);
00455             }
00456 
00457             if (!$backwards) {
00458                 $relativeDate = sprintf(__('%s ago', true), $relativeDate);
00459             }
00460         }
00461         return $this->output($relativeDate);
00462     }
00463 /**
00464  * Alias for timeAgoInWords
00465  *
00466  * @param mixed $dateTime Datetime string (strtotime-compatible) or Unix timestamp
00467  * @param mixed $options Default format string, if timestamp is used in $dateTime, or an array of options to be passed
00468  *   on to timeAgoInWords().
00469  * @return string Relative time string.
00470  * @see     TimeHelper::timeAgoInWords
00471  */
00472     function relativeTime($dateTime, $options = array()) {
00473         return $this->timeAgoInWords($dateTime, $options);
00474     }
00475 /**
00476  * Returns true if specified datetime was within the interval specified, else false.
00477  *
00478  * @param mixed $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
00479  * @param mixed $dateString the datestring or unix timestamp to compare
00480  * @param int $userOffset User's offset from GMT (in hours)
00481  * @return bool
00482  */
00483     function wasWithinLast($timeInterval, $dateString, $userOffset = null) {
00484         $tmp = str_replace(' ', '', $timeInterval);
00485         if (is_numeric($tmp)) {
00486             $timeInterval = $tmp . ' ' . __('days', true);
00487         }
00488 
00489         $date = $this->fromString($dateString, $userOffset);
00490         $interval = $this->fromString('-'.$timeInterval);
00491 
00492         if ($date >= $interval && $date <= time()) {
00493             return true;
00494         }
00495 
00496         return false;
00497     }
00498 /**
00499  * Returns gmt, given either a UNIX timestamp or a valid strtotime() date string.
00500  *
00501  * @param string $dateString Datetime string
00502  * @return string Formatted date string
00503  */
00504     function gmt($string = null) {
00505         if ($string != null) {
00506             $string = $this->fromString($string);
00507         } else {
00508             $string = time();
00509         }
00510         $string = $this->fromString($string);
00511         $hour = intval(date("G", $string));
00512         $minute = intval(date("i", $string));
00513         $second = intval(date("s", $string));
00514         $month = intval(date("n", $string));
00515         $day = intval(date("j", $string));
00516         $year = intval(date("Y", $string));
00517 
00518         $return = gmmktime($hour, $minute, $second, $month, $day, $year);
00519         return $return;
00520     }
00521 /**
00522  * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
00523  *
00524  * @param string $format date format string. defaults to 'd-m-Y'
00525  * @param string $dateString Datetime string
00526  * @param boolean $invalid flag to ignore results of fromString == false
00527  * @param int $userOffset User's offset from GMT (in hours)
00528  * @return string Formatted date string
00529  */
00530     function format($format = 'd-m-Y', $date, $invalid = false, $userOffset = null) {
00531         $date = $this->fromString($date, $userOffset);
00532         if ($date === false && $invalid !== false) {
00533             return $invalid;
00534         }
00535         return date($format, $date);
00536     }
00537 }
00538 ?>

Generated on Sun Nov 22 00:30:54 2009 for CakePHP 1.2.x.x (v1.2.4.8284) by doxygen 1.4.7