1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Utils;
9:
10: use Nette;
11:
12:
13: 14: 15:
16: class DateTime extends \DateTime implements \JsonSerializable
17: {
18: use Nette\SmartObject;
19:
20:
21: const MINUTE = 60;
22:
23:
24: const HOUR = 60 * self::MINUTE;
25:
26:
27: const DAY = 24 * self::HOUR;
28:
29:
30: const WEEK = 7 * self::DAY;
31:
32:
33: const MONTH = 2629800;
34:
35:
36: const YEAR = 31557600;
37:
38:
39: 40: 41: 42: 43:
44: public static function from($time)
45: {
46: if ($time instanceof \DateTimeInterface) {
47: return new static($time->format('Y-m-d H:i:s.u'), $time->getTimezone());
48:
49: } elseif (is_numeric($time)) {
50: if ($time <= self::YEAR) {
51: $time += time();
52: }
53: return (new static('@' . $time))->setTimezone(new \DateTimeZone(date_default_timezone_get()));
54:
55: } else {
56: return new static($time);
57: }
58: }
59:
60:
61: 62: 63: 64:
65: public static function fromParts($year, $month, $day, $hour = 0, $minute = 0, $second = 0)
66: {
67: $s = sprintf('%04d-%02d-%02d %02d:%02d:%02.5f', $year, $month, $day, $hour, $minute, $second);
68: if (!checkdate($month, $day, $year) || $hour < 0 || $hour > 23 || $minute < 0 || $minute > 59 || $second < 0 || $second >= 60) {
69: throw new Nette\InvalidArgumentException("Invalid date '$s'");
70: }
71: return new static($s);
72: }
73:
74:
75: 76: 77: 78: 79: 80: 81:
82: public static function createFromFormat($format, $time, $timezone = null)
83: {
84: if ($timezone === null) {
85: $timezone = new \DateTimeZone(date_default_timezone_get());
86:
87: } elseif (is_string($timezone)) {
88: $timezone = new \DateTimeZone($timezone);
89:
90: } elseif (!$timezone instanceof \DateTimeZone) {
91: throw new Nette\InvalidArgumentException('Invalid timezone given');
92: }
93:
94: $date = parent::createFromFormat($format, $time, $timezone);
95: return $date ? static::from($date) : false;
96: }
97:
98:
99: 100: 101: 102:
103: public function jsonSerialize()
104: {
105: return $this->format('c');
106: }
107:
108:
109: 110: 111:
112: public function __toString()
113: {
114: return $this->format('Y-m-d H:i:s');
115: }
116:
117:
118: 119: 120: 121:
122: public function modifyClone($modify = '')
123: {
124: $dolly = clone $this;
125: return $modify ? $dolly->modify($modify) : $dolly;
126: }
127:
128:
129: 130: 131: 132:
133: public function setTimestamp($timestamp)
134: {
135: $zone = $this->getTimezone();
136: $this->__construct('@' . $timestamp);
137: return $this->setTimezone($zone);
138: }
139:
140:
141: 142: 143:
144: public function getTimestamp()
145: {
146: $ts = $this->format('U');
147: return is_float($tmp = $ts * 1) ? $ts : $tmp;
148: }
149: }
150: