1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
6: * @package Nette
7: */
8:
9:
10:
11: /**
12: * DateTime with serialization and timestamp support for PHP 5.2.
13: *
14: * @author David Grudl
15: * @package Nette
16: */
17: class NDateTime53 extends DateTime
18: {
19: /** minute in seconds */
20: const MINUTE = 60;
21:
22: /** hour in seconds */
23: const HOUR = 3600;
24:
25: /** day in seconds */
26: const DAY = 86400;
27:
28: /** week in seconds */
29: const WEEK = 604800;
30:
31: /** average month in seconds */
32: const MONTH = 2629800;
33:
34: /** average year in seconds */
35: const YEAR = 31557600;
36:
37:
38: /**
39: * DateTime object factory.
40: * @param string|int|DateTime
41: * @return NDateTime53
42: */
43: public static function from($time)
44: {
45: if ($time instanceof DateTime || $time instanceof DateTimeInterface) {
46: return new self($time->format('Y-m-d H:i:s'), $time->getTimezone());
47:
48: } elseif (is_numeric($time)) {
49: if ($time <= self::YEAR) {
50: $time += time();
51: }
52: $tmp = new self('@' . $time);
53: $tmp->setTimeZone(new DateTimeZone(date_default_timezone_get()));
54: return $tmp;
55:
56: } else { // textual or NULL
57: return new self($time);
58: }
59: }
60:
61:
62: /**
63: * @return string
64: */
65: public function __toString()
66: {
67: return $this->format('Y-m-d H:i:s');
68: }
69:
70:
71: /**
72: * @param string
73: * @return self
74: */
75: public function modifyClone($modify = '')
76: {
77: $dolly = clone $this;
78: return $modify ? $dolly->modify($modify) : $dolly;
79: }
80:
81:
82: /**
83: * @param int
84: * @return self
85: */
86: public function setTimestamp($timestamp)
87: {
88: $zone = PHP_VERSION_ID === 50206 ? new DateTimeZone($this->getTimezone()->getName()) : $this->getTimezone();
89: $this->__construct('@' . $timestamp);
90: $this->setTimeZone($zone);
91: return $this;
92: }
93:
94:
95: /**
96: * @return int|string
97: */
98: public function getTimestamp()
99: {
100: $ts = $this->format('U');
101: return is_float($tmp = $ts * 1) ? $ts : $tmp;
102: }
103:
104:
105: public function modify($modify)
106: {
107: parent::modify($modify);
108: return $this;
109: }
110:
111:
112: public static function __set_state($state)
113: {
114: return new self($state['date'], new DateTimeZone($state['timezone']));
115: }
116:
117:
118: public function __sleep()
119: {
120: $zone = $this->getTimezone()->getName();
121: if ($zone[0] === '+') {
122: $this->fix = array($this->format('Y-m-d H:i:sP'));
123: } else {
124: $this->fix = array($this->format('Y-m-d H:i:s'), $zone);
125: }
126: return array('fix');
127: }
128:
129:
130: public function __wakeup()
131: {
132: if (isset($this->fix[1])) {
133: $this->__construct($this->fix[0], new DateTimeZone($this->fix[1]));
134: } else {
135: $this->__construct($this->fix[0]);
136: }
137: unset($this->fix);
138: }
139:
140: }
141: