Subversion-Projekte lars-tiefland.cakephp

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/* SVN FILE: $Id: time.php 7945 2008-12-19 02:16:01Z gwoo $ */
3
/**
4
 * Time Helper class file.
5
 *
6
 * PHP versions 4 and 5
7
 *
8
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
9
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
10
 *
11
 * Licensed under The MIT License
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @filesource
15
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
16
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
17
 * @package       cake
18
 * @subpackage    cake.cake.libs.view.helpers
19
 * @since         CakePHP(tm) v 0.10.0.1076
20
 * @version       $Revision: 7945 $
21
 * @modifiedby    $LastChangedBy: gwoo $
22
 * @lastmodified  $Date: 2008-12-18 18:16:01 -0800 (Thu, 18 Dec 2008) $
23
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
24
 */
25
/**
26
 * Time Helper class for easy use of time data.
27
 *
28
 * Manipulation of time data.
29
 *
30
 * @package       cake
31
 * @subpackage    cake.cake.libs.view.helpers
32
 */
33
class TimeHelper extends AppHelper {
34
/**
35
 * Converts given time (in server's time zone) to user's local time, given his/her offset from GMT.
36
 *
37
 * @param string $serverTime UNIX timestamp
38
 * @param int $userOffset User's offset from GMT (in hours)
39
 * @return string UNIX timestamp
40
 */
41
	function convert($serverTime, $userOffset) {
42
		$serverOffset = $this->serverOffset();
43
		$gmtTime = $serverTime - $serverOffset;
44
		$userTime = $gmtTime + $userOffset * (60*60);
45
		return $userTime;
46
	}
47
/**
48
 * Returns server's offset from GMT in seconds.
49
 *
50
 * @return int Offset
51
 */
52
	function serverOffset() {
53
		return date('Z', time());
54
	}
55
/**
56
 * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
57
 *
58
 * @param string $dateString Datetime string
59
 * @param int $userOffset User's offset from GMT (in hours)
60
 * @return string Parsed timestamp
61
 */
62
	function fromString($dateString, $userOffset = null) {
63
		if (empty($dateString)) {
64
			return false;
65
		}
66
		if (is_integer($dateString) || is_numeric($dateString)) {
67
			$date = intval($dateString);
68
		} else {
69
			$date = strtotime($dateString);
70
		}
71
		if ($userOffset !== null) {
72
			return $this->convert($date, $userOffset);
73
		}
74
		return $date;
75
	}
76
/**
77
 * Returns a nicely formatted date string for given Datetime string.
78
 *
79
 * @param string $dateString Datetime string or Unix timestamp
80
 * @param int $userOffset User's offset from GMT (in hours)
81
 * @return string Formatted date string
82
 */
83
	function nice($dateString = null, $userOffset = null) {
84
		if ($dateString != null) {
85
			$date = $this->fromString($dateString, $userOffset);
86
		} else {
87
			$date = time();
88
		}
89
 
90
		$ret = date("D, M jS Y, H:i", $date);
91
		return $this->output($ret);
92
	}
93
/**
94
 * Returns a formatted descriptive date string for given datetime string.
95
 *
96
 * If the given date is today, the returned string could be "Today, 16:54".
97
 * If the given date was yesterday, the returned string could be "Yesterday, 16:54".
98
 * If $dateString's year is the current year, the returned string does not
99
 * include mention of the year.
100
 *
101
 * @param string $dateString Datetime string or Unix timestamp
102
 * @param int $userOffset User's offset from GMT (in hours)
103
 * @return string Described, relative date string
104
 */
105
	function niceShort($dateString = null, $userOffset = null) {
106
		$date = $dateString ? $this->fromString($dateString, $userOffset) : time();
107
 
108
		$y = $this->isThisYear($date) ? '' : ' Y';
109
 
110
		if ($this->isToday($date)) {
111
			$ret = sprintf(__('Today, %s',true), date("H:i", $date));
112
		} elseif ($this->wasYesterday($date)) {
113
			$ret = sprintf(__('Yesterday, %s',true), date("H:i", $date));
114
		} else {
115
			$ret = date("M jS{$y}, H:i", $date);
116
		}
117
 
118
		return $this->output($ret);
119
	}
120
/**
121
 * Returns a partial SQL string to search for all records between two dates.
122
 *
123
 * @param string $dateString Datetime string or Unix timestamp
124
 * @param string $end Datetime string or Unix timestamp
125
 * @param string $fieldName Name of database field to compare with
126
 * @param int $userOffset User's offset from GMT (in hours)
127
 * @return string Partial SQL string.
128
 */
129
	function daysAsSql($begin, $end, $fieldName, $userOffset = null) {
130
		$begin = $this->fromString($begin, $userOffset);
131
		$end = $this->fromString($end, $userOffset);
132
		$begin = date('Y-m-d', $begin) . ' 00:00:00';
133
		$end = date('Y-m-d', $end) . ' 23:59:59';
134
 
135
		$ret  ="($fieldName >= '$begin') AND ($fieldName <= '$end')";
136
		return $this->output($ret);
137
	}
138
/**
139
 * Returns a partial SQL string to search for all records between two times
140
 * occurring on the same day.
141
 *
142
 * @param string $dateString Datetime string or Unix timestamp
143
 * @param string $fieldName Name of database field to compare with
144
 * @param int $userOffset User's offset from GMT (in hours)
145
 * @return string Partial SQL string.
146
 */
147
	function dayAsSql($dateString, $fieldName, $userOffset = null) {
148
		$date = $this->fromString($dateString, $userOffset);
149
		$ret = $this->daysAsSql($dateString, $dateString, $fieldName);
150
		return $this->output($ret);
151
	}
152
/**
153
 * Returns true if given datetime string is today.
154
 *
155
 * @param string $dateString Datetime string or Unix timestamp
156
 * @param int $userOffset User's offset from GMT (in hours)
157
 * @return boolean True if datetime string is today
158
 */
159
	function isToday($dateString, $userOffset = null) {
160
		$date = $this->fromString($dateString, $userOffset);
161
		return date('Y-m-d', $date) == date('Y-m-d', time());
162
	}
163
/**
164
 * Returns true if given datetime string is within this week
165
 * @param string $dateString
166
 * @param int $userOffset User's offset from GMT (in hours)
167
 * @return boolean True if datetime string is within current week
168
 */
169
	function isThisWeek($dateString, $userOffset = null) {
170
		$date = $this->fromString($dateString, $userOffset);
171
		return date('W Y', $date) == date('W Y', time());
172
	}
173
/**
174
 * Returns true if given datetime string is within this month
175
 * @param string $dateString
176
 * @param int $userOffset User's offset from GMT (in hours)
177
 * @return boolean True if datetime string is within current month
178
 */
179
	function isThisMonth($dateString, $userOffset = null) {
180
		$date = $this->fromString($dateString);
181
		return date('m Y',$date) == date('m Y', time());
182
	}
183
/**
184
 * Returns true if given datetime string is within current year.
185
 *
186
 * @param string $dateString Datetime string or Unix timestamp
187
 * @return boolean True if datetime string is within current year
188
 */
189
	function isThisYear($dateString, $userOffset = null) {
190
		$date = $this->fromString($dateString, $userOffset);
191
		return  date('Y', $date) == date('Y', time());
192
	}
193
/**
194
 * Returns true if given datetime string was yesterday.
195
 *
196
 * @param string $dateString Datetime string or Unix timestamp
197
 * @param int $userOffset User's offset from GMT (in hours)
198
 * @return boolean True if datetime string was yesterday
199
 */
200
	function wasYesterday($dateString, $userOffset = null) {
201
		$date = $this->fromString($dateString, $userOffset);
202
		return date('Y-m-d', $date) == date('Y-m-d', strtotime('yesterday'));
203
	}
204
/**
205
 * Returns true if given datetime string is tomorrow.
206
 *
207
 * @param string $dateString Datetime string or Unix timestamp
208
 * @param int $userOffset User's offset from GMT (in hours)
209
 * @return boolean True if datetime string was yesterday
210
 */
211
	function isTomorrow($dateString, $userOffset = null) {
212
		$date = $this->fromString($dateString, $userOffset);
213
		return date('Y-m-d', $date) == date('Y-m-d', strtotime('tomorrow'));
214
	}
215
/**
216
 * Returns the quart
217
 * @param string $dateString
218
 * @param boolean $range if true returns a range in Y-m-d format
219
 * @return boolean True if datetime string is within current week
220
 */
221
	function toQuarter($dateString, $range = false) {
222
		$time = $this->fromString($dateString);
223
		$date = ceil(date('m', $time) / 3);
224
 
225
		if ($range === true) {
226
			$range = 'Y-m-d';
227
		}
228
 
229
		if ($range !== false) {
230
			$year = date('Y', $time);
231
 
232
			switch ($date) {
233
				case 1:
234
					$date = array($year.'-01-01', $year.'-03-31');
235
					break;
236
				case 2:
237
					$date = array($year.'-04-01', $year.'-06-30');
238
					break;
239
				case 3:
240
					$date = array($year.'-07-01', $year.'-09-30');
241
					break;
242
				case 4:
243
					$date = array($year.'-10-01', $year.'-12-31');
244
					break;
245
			}
246
		}
247
		return $this->output($date);
248
	}
249
/**
250
 * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime().
251
 *
252
 * @param string $dateString Datetime string to be represented as a Unix timestamp
253
 * @param int $userOffset User's offset from GMT (in hours)
254
 * @return integer Unix timestamp
255
 */
256
	function toUnix($dateString, $userOffset = null) {
257
		$ret = $this->fromString($dateString, $userOffset);
258
		return $this->output($ret);
259
	}
260
/**
261
 * Returns a date formatted for Atom RSS feeds.
262
 *
263
 * @param string $dateString Datetime string or Unix timestamp
264
 * @param int $userOffset User's offset from GMT (in hours)
265
 * @return string Formatted date string
266
 */
267
	function toAtom($dateString, $userOffset = null) {
268
		$date = $this->fromString($dateString, $userOffset);
269
		$ret = date('Y-m-d\TH:i:s\Z', $date);
270
		return $this->output($ret);
271
	}
272
/**
273
 * Formats date for RSS feeds
274
 *
275
 * @param string $dateString Datetime string or Unix timestamp
276
 * @param int $userOffset User's offset from GMT (in hours)
277
 * @return string Formatted date string
278
 */
279
	function toRSS($dateString, $userOffset = null) {
280
		$date = $this->fromString($dateString, $userOffset);
281
		$ret = date("r", $date);
282
		return $this->output($ret);
283
	}
284
/**
285
 * Returns either a relative date or a formatted date depending
286
 * on the difference between the current time and given datetime.
287
 * $datetime should be in a <i>strtotime</i>-parsable format, like MySQL's datetime datatype.
288
 *
289
 * Options:
290
 *  'format' => a fall back format if the relative time is longer than the duration specified by end
291
 *  'end' =>  The end of relative time telling
292
 *  'userOffset' => Users offset from GMT (in hours)
293
 *
294
 * Relative dates look something like this:
295
 *	3 weeks, 4 days ago
296
 *	15 seconds ago
297
 * Formatted dates look like this:
298
 *	on 02/18/2004
299
 *
300
 * The returned string includes 'ago' or 'on' and assumes you'll properly add a word
301
 * like 'Posted ' before the function output.
302
 *
303
 * @param string $dateString Datetime string or Unix timestamp
304
 * @param array $options Default format if timestamp is used in $dateString
305
 * @return string Relative time string.
306
 */
307
	function timeAgoInWords($dateTime, $options = array()) {
308
		$userOffset = null;
309
		if (is_array($options) && isset($options['userOffset'])) {
310
			$userOffset = $options['userOffset'];
311
		}
312
		$now = time();
313
		if (!is_null($userOffset)) {
314
			$now = 	$this->convert(time(), $userOffset);
315
		}
316
		$inSeconds = $this->fromString($dateTime, $userOffset);
317
		$backwards = ($inSeconds > $now);
318
 
319
		$format = 'j/n/y';
320
		$end = '+1 month';
321
 
322
		if (is_array($options)) {
323
			if (isset($options['format'])) {
324
				$format = $options['format'];
325
				unset($options['format']);
326
			}
327
			if (isset($options['end'])) {
328
				$end = $options['end'];
329
				unset($options['end']);
330
			}
331
		} else {
332
			$format = $options;
333
		}
334
 
335
		if ($backwards) {
336
			$futureTime = $inSeconds;
337
			$pastTime = $now;
338
		} else {
339
			$futureTime = $now;
340
			$pastTime = $inSeconds;
341
		}
342
		$diff = $futureTime - $pastTime;
343
 
344
		// If more than a week, then take into account the length of months
345
		if ($diff >= 604800) {
346
			$current = array();
347
			$date = array();
348
 
349
			list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime));
350
 
351
			list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime));
352
			$years = $months = $weeks = $days = $hours = $minutes = $seconds = 0;
353
 
354
			if ($future['Y'] == $past['Y'] && $future['m'] == $past['m']) {
355
				$months = 0;
356
				$years = 0;
357
			} else {
358
				if ($future['Y'] == $past['Y']) {
359
					$months = $future['m'] - $past['m'];
360
				} else {
361
					$years = $future['Y'] - $past['Y'];
362
					$months = $future['m'] + ((12 * $years) - $past['m']);
363
 
364
					if ($months >= 12) {
365
						$years = floor($months / 12);
366
						$months = $months - ($years * 12);
367
					}
368
 
369
					if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] == 1) {
370
						$years --;
371
					}
372
				}
373
			}
374
 
375
			if ($future['d'] >= $past['d']) {
376
				$days = $future['d'] - $past['d'];
377
			} else {
378
				$daysInPastMonth = date('t', $pastTime);
379
				$daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y']));
380
 
381
				if (!$backwards) {
382
					$days = ($daysInPastMonth - $past['d']) + $future['d'];
383
				} else {
384
					$days = ($daysInFutureMonth - $past['d']) + $future['d'];
385
				}
386
 
387
				if ($future['m'] != $past['m']) {
388
					$months --;
389
				}
390
			}
391
 
392
			if ($months == 0 && $years >= 1 && $diff < ($years * 31536000)) {
393
				$months = 11;
394
				$years --;
395
			}
396
 
397
			if ($months >= 12) {
398
				$years = $years + 1;
399
				$months = $months - 12;
400
			}
401
 
402
			if ($days >= 7) {
403
				$weeks = floor($days / 7);
404
				$days = $days - ($weeks * 7);
405
			}
406
		} else {
407
			$years = $months = $weeks = 0;
408
			$days = floor($diff / 86400);
409
 
410
			$diff = $diff - ($days * 86400);
411
 
412
			$hours = floor($diff / 3600);
413
			$diff = $diff - ($hours * 3600);
414
 
415
			$minutes = floor($diff / 60);
416
			$diff = $diff - ($minutes * 60);
417
			$seconds = $diff;
418
		}
419
		$relativeDate = '';
420
		$diff = $futureTime - $pastTime;
421
 
422
		if ($diff > abs($now - $this->fromString($end))) {
423
			$relativeDate = sprintf(__('on %s',true), date($format, $inSeconds));
424
		} else {
425
			if ($years > 0) {
426
				// years and months and days
427
				$relativeDate .= ($relativeDate ? ', ' : '') . $years . ' ' . __n('year', 'years', $years, true);
428
				$relativeDate .= $months > 0 ? ($relativeDate ? ', ' : '') . $months . ' ' . __n('month', 'months', $months, true) : '';
429
				$relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks, true) : '';
430
				$relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true) : '';
431
			} elseif (abs($months) > 0) {
432
				// months, weeks and days
433
				$relativeDate .= ($relativeDate ? ', ' : '') . $months . ' ' . __n('month', 'months', $months, true);
434
				$relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks, true) : '';
435
				$relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true) : '';
436
			} elseif (abs($weeks) > 0) {
437
				// weeks and days
438
				$relativeDate .= ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks, true);
439
				$relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true) : '';
440
			} elseif (abs($days) > 0) {
441
				// days and hours
442
				$relativeDate .= ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true);
443
				$relativeDate .= $hours > 0 ? ($relativeDate ? ', ' : '') . $hours . ' ' . __n('hour', 'hours', $hours, true) : '';
444
			} elseif (abs($hours) > 0) {
445
				// hours and minutes
446
				$relativeDate .= ($relativeDate ? ', ' : '') . $hours . ' ' . __n('hour', 'hours', $hours, true);
447
				$relativeDate .= $minutes > 0 ? ($relativeDate ? ', ' : '') . $minutes . ' ' . __n('minute', 'minutes', $minutes, true) : '';
448
			} elseif (abs($minutes) > 0) {
449
				// minutes only
450
				$relativeDate .= ($relativeDate ? ', ' : '') . $minutes . ' ' . __n('minute', 'minutes', $minutes, true);
451
			} else {
452
				// seconds only
453
				$relativeDate .= ($relativeDate ? ', ' : '') . $seconds . ' ' . __n('second', 'seconds', $seconds, true);
454
			}
455
 
456
			if (!$backwards) {
457
				$relativeDate = sprintf(__('%s ago', true), $relativeDate);
458
			}
459
		}
460
		return $this->output($relativeDate);
461
	}
462
/**
463
 * Alias for timeAgoInWords
464
 *
465
 * @param mixed $dateTime Datetime string (strtotime-compatible) or Unix timestamp
466
 * @param mixed $options Default format string, if timestamp is used in $dateTime, or an array of options to be passed
467
 *						 on to timeAgoInWords().
468
 * @return string Relative time string.
469
 * @see		TimeHelper::timeAgoInWords
470
 */
471
	function relativeTime($dateTime, $options = array()) {
472
		return $this->timeAgoInWords($dateTime, $options);
473
	}
474
/**
475
 * Returns true if specified datetime was within the interval specified, else false.
476
 *
477
 * @param mixed $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
478
 * @param mixed $dateString the datestring or unix timestamp to compare
479
 * @param int $userOffset User's offset from GMT (in hours)
480
 * @return bool
481
 */
482
	function wasWithinLast($timeInterval, $dateString, $userOffset = null) {
483
		$tmp = r(' ', '', $timeInterval);
484
		if (is_numeric($tmp)) {
485
			$timeInterval = $tmp . ' ' . __('days', true);
486
		}
487
 
488
		$date = $this->fromString($dateString, $userOffset);
489
		$interval = $this->fromString('-'.$timeInterval);
490
 
491
		if ($date >= $interval && $date <= time()) {
492
			return true;
493
		}
494
 
495
		return false;
496
	}
497
/**
498
 * Returns gmt, given either a UNIX timestamp or a valid strtotime() date string.
499
 *
500
 * @param string $dateString Datetime string
501
 * @return string Formatted date string
502
 */
503
	function gmt($string = null) {
504
		if ($string != null) {
505
			$string = $this->fromString($string);
506
		} else {
507
			$string = time();
508
		}
509
		$string = $this->fromString($string);
510
		$hour = intval(date("G", $string));
511
		$minute = intval(date("i", $string));
512
		$second = intval(date("s", $string));
513
		$month = intval(date("n", $string));
514
		$day = intval(date("j", $string));
515
		$year = intval(date("Y", $string));
516
 
517
		$return = gmmktime($hour, $minute, $second, $month, $day, $year);
518
		return $return;
519
	}
520
/**
521
 * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
522
 *
523
 * @param string $format date format string. defaults to 'd-m-Y'
524
 * @param string $dateString Datetime string
525
 * @param boolean $invalid flag to ignore results of fromString == false
526
 * @param int $userOffset User's offset from GMT (in hours)
527
 * @return string Formatted date string
528
 */
529
	function format($format = 'd-m-Y', $date, $invalid = false, $userOffset = null) {
530
		$date = $this->fromString($date, $userOffset);
531
		if ($date === false && $invalid !== false) {
532
			return $invalid;
533
		}
534
		return date($format, $date);
535
	}
536
}
537
?>