1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6: */
7:
8: namespace Nette\Utils;
9:
10: use Nette;
11:
12:
13: /**
14: * DateTime.
15: */
16: class DateTime extends \DateTime
17: {
18: /** minute in seconds */
19: const MINUTE = 60;
20:
21: /** hour in seconds */
22: const HOUR = 3600;
23:
24: /** day in seconds */
25: const DAY = 86400;
26:
27: /** week in seconds */
28: const WEEK = 604800;
29:
30: /** average month in seconds */
31: const MONTH = 2629800;
32:
33: /** average year in seconds */
34: const YEAR = 31557600;
35:
36:
37: /**
38: * DateTime object factory.
39: * @param string|int|\DateTime
40: * @return static
41: */
42: public static function from($time)
43: {
44: if ($time instanceof \DateTime || $time instanceof \DateTimeInterface) {
45: return new static($time->format('Y-m-d H:i:s'), $time->getTimezone());
46:
47: } elseif (is_numeric($time)) {
48: if ($time <= self::YEAR) {
49: $time += time();
50: }
51: $tmp = new static('@' . $time);
52: return $tmp->setTimeZone(new \DateTimeZone(date_default_timezone_get()));
53:
54: } else { // textual or NULL
55: return new static($time);
56: }
57: }
58:
59:
60: /**
61: * @return string
62: */
63: public function __toString()
64: {
65: return $this->format('Y-m-d H:i:s');
66: }
67:
68:
69: /**
70: * @param string
71: * @return static
72: */
73: public function modifyClone($modify = '')
74: {
75: $dolly = clone $this;
76: return $modify ? $dolly->modify($modify) : $dolly;
77: }
78:
79:
80: /**
81: * @param int
82: * @return static
83: */
84: public function setTimestamp($timestamp)
85: {
86: $zone = $this->getTimezone();
87: $this->__construct('@' . $timestamp);
88: return $this->setTimeZone($zone);
89: }
90:
91:
92: /**
93: * @return int|string
94: */
95: public function getTimestamp()
96: {
97: $ts = $this->format('U');
98: return is_float($tmp = $ts * 1) ? $ts : $tmp;
99: }
100:
101:
102: /**
103: * Returns new DateTime object formatted according to the specified format.
104: * @param string The format the $time parameter should be in
105: * @param string String representing the time
106: * @param string|\DateTimeZone desired timezone (default timezone is used if NULL is passed)
107: * @return static|FALSE
108: */
109: public static function createFromFormat($format, $time, $timezone = NULL)
110: {
111: if ($timezone === NULL) {
112: $timezone = new \DateTimeZone(date_default_timezone_get());
113:
114: } elseif (is_string($timezone)) {
115: $timezone = new \DateTimeZone($timezone);
116:
117: } elseif (!$timezone instanceof \DateTimeZone) {
118: throw new Nette\InvalidArgumentException('Invalid timezone given');
119: }
120:
121: $date = parent::createFromFormat($format, $time, $timezone);
122: return $date ? static::from($date) : FALSE;
123: }
124:
125: }
126: