Bitrix-D7  20.0.0
main/lib/type/date.php
См. документацию.
1 <?php
2 namespace Bitrix\Main\Type;
3 
4 use Bitrix\Main;
6 
7 class Date
8 {
9  /** @var \DateTime */
10  protected $value;
11 
12  /**
13  * @param string $date String representation of date.
14  * @param string $format PHP date format. If not specified, the format is got from the current culture.
15  *
16  * @throws Main\ObjectException
17  */
18  public function __construct($date = null, $format = null)
19  {
20  $this->value = new \DateTime();
21  if ($date !== null && $date !== "")
22  {
23  if ($format === null)
24  {
25  $format = static::getFormat();
26  }
27 
28  $parsedValue = date_parse_from_format($format, $date);
29  //Ignore errors when format is longer than date
30  //or date string is longer than format
31  if ($parsedValue['error_count'] > 1)
32  {
33  if (
34  current($parsedValue['errors']) !== 'Trailing data'
35  && current($parsedValue['errors']) !== 'Data missing'
36  )
37  {
38  throw new Main\ObjectException("Incorrect date: ".$date);
39  }
40  }
41 
42  $this->value->setDate($parsedValue['year'], $parsedValue['month'], $parsedValue['day']);
43 
44  if (
45  isset($parsedValue["relative"])
46  && isset($parsedValue["relative"]["second"])
47  && $parsedValue["relative"]["second"] != 0
48  )
49  {
50  $this->value->add(new \DateInterval("PT".$parsedValue["relative"]["second"]."S"));
51  }
52  }
53  $this->value->setTime(0, 0, 0);
54  }
55 
56  /**
57  * Formats date value to string.
58  *
59  * @param string $format PHP date format.
60  *
61  * @return string
62  */
63  public function format($format)
64  {
65  return $this->value->format($format);
66  }
67 
68  /**
69  * Produces the copy of the object.
70  *
71  * @return void
72  */
73  public function __clone()
74  {
75  $this->value = clone $this->value;
76  }
77 
78  /**
79  * Performs dates arithmetic.
80  *
81  * Each duration period is represented by an integer value followed by a period
82  * designator. If the duration contains time elements, that portion of the
83  * specification is preceded by the letter T.
84  * Period Designators: Y - years, M - months, D - days, W - weeks, H - hours,
85  * M - minutes, S - seconds.
86  * Examples: two days - 2D, two seconds - T2S, six years and five minutes - 6YT5M.
87  * The unit types must be entered from the largest scale unit on the left to the
88  * smallest scale unit on the right.
89  * Use first "-" char for negative periods.
90  * OR
91  * Relative period.
92  * Examples: "+5 weeks", "12 day", "-7 weekdays", '3 months - 5 days'
93  *
94  * @param string $interval Time interval to add.
95  *
96  * @return $this
97  */
98  public function add($interval)
99  {
100  $i = $this->tryToCreateIntervalByDesignators($interval);
101  if ($i == null)
102  {
103  $i = \DateInterval::createFromDateString($interval);
104  }
105 
106  $this->value->add($i);
107 
108  return $this;
109  }
110 
111  /**
112  * Sets the current date of the DateTime object to a different date.
113  * @param int $year
114  * @param int $month
115  * @param int $day
116  *
117  * @return $this
118  */
119  public function setDate($year, $month, $day)
120  {
121  $this->value->setDate($year, $month, $day);
122 
123  return $this;
124  }
125 
126  private function tryToCreateIntervalByDesignators($interval)
127  {
128  if (!is_string($interval) || strpos($interval, ' ') !== false)
129  {
130  return null;
131  }
132 
133  $i = null;
134  try
135  {
136  $intervalTmp = strtoupper($interval);
137  $isNegative = false;
138  $firstChar = substr($intervalTmp, 0, 1);
139  if ($firstChar === "-")
140  {
141  $isNegative = true;
142  $intervalTmp = substr($intervalTmp, 1);
143  $firstChar = substr($intervalTmp, 0, 1);
144  }
145 
146  if ($firstChar !== "P")
147  {
148  $intervalTmp = "P".$intervalTmp;
149  }
150  $i = new \DateInterval($intervalTmp);
151  if ($isNegative)
152  {
153  $i->invert = 1;
154  }
155  }
156  catch (\Exception $e)
157  {
158  }
159 
160  return $i;
161  }
162 
163  /**
164  * Returns Unix timestamp from date.
165  *
166  * @return int
167  */
168  public function getTimestamp()
169  {
170  return $this->value->getTimestamp();
171  }
172 
173  /**
174  * Returns difference between dates.
175  *
176  * @param DateTime $time
177  * @return \DateInterval
178  */
179  public function getDiff(DateTime $time)
180  {
181  return $this->value->diff($time->value);
182  }
183 
184  /**
185  * Converts a date to the string.
186  *
187  * @param Context\Culture $culture Culture contains date format.
188  *
189  * @return string
190  */
191  public function toString(Context\Culture $culture = null)
192  {
193  $format = static::getFormat($culture);
194  return $this->format($format);
195  }
196 
197  /**
198  * Converts a date to the string with default culture format setting.
199  *
200  * @return string
201  */
202  public function __toString()
203  {
204  return $this->toString();
205  }
206 
207  /**
208  * Returns a date format from the culture in the php format.
209  *
210  * @param Context\Culture $culture Optional culture.
211  *
212  * @return string
213  */
214  public static function getFormat(Context\Culture $culture = null)
215  {
216  static $defaultCulture = null;
217 
218  if($culture === null)
219  {
220  if($defaultCulture === null)
221  {
222  $context = Context::getCurrent();
223  $defaultCulture = $context->getCulture();
224  }
225  $culture = $defaultCulture;
226  }
227 
228  $format = static::getCultureFormat($culture);
229 
230  return static::convertFormatToPhp($format);
231  }
232 
233  /**
234  * Returns short date culture format.
235  *
236  * @param Context\Culture $culture Culture.
237  *
238  * @return string
239  */
240  protected static function getCultureFormat(Context\Culture $culture)
241  {
242  return $culture->getDateFormat();
243  }
244 
245  /**
246  * Converts date format from culture to php format.
247  *
248  * @param string $format Format string.
249  *
250  * @return mixed
251  */
252  public static function convertFormatToPhp($format)
253  {
254  static $from = array(
255  "YYYY", // 1999
256  "MMMM", // January - December
257  "MM", // 01 - 12
258  "DD", // 01 - 31
259  "TT", // AM - PM
260  "T", // am - pm
261  "MI", // 00 - 59
262  "SS", // 00 - 59
263  );
264  static $to = array(
265  "Y", // 1999
266  "F", // January - December
267  "m", // 01 - 12
268  "d", // 01 - 31
269  "A", // AM - PM
270  "a", // am - pm
271  "i", // 00 - 59
272  "s", // 00 - 59
273  );
274 
275  $format = str_replace($from, $to, $format);
276 
277  $tempFormat = $format;
278  $format = str_replace("HH", "H", $format); // 00 - 24
279  if ($tempFormat === $format)
280  {
281  $format = str_replace("H", "h", $format); // 01 - 12
282  }
283 
284  $tempFormat = $format;
285  $format = str_replace("GG", "G", $format); // 0 - 24
286  if ($tempFormat === $format)
287  {
288  $format = str_replace("G", "g", $format); // 1 - 12
289  }
290 
291  return $format;
292  }
293 
294  /**
295  * Checks the string for correct date (by trying to create Date object).
296  *
297  * @param string $time String representation of date.
298  * @param string $format PHP date format. If not specified, the format is got from the current culture.
299  *
300  * @return bool
301  */
302  public static function isCorrect($time, $format = null)
303  {
304  if (empty($time))
305  {
306  return false;
307  }
308 
309  $result = true;
310 
311  try
312  {
313  new static($time, $format);
314  }
315  catch (Main\ObjectException $ex)
316  {
317  $result = false;
318  }
319 
320  return $result;
321  }
322 
323  /**
324  * Creates Date object from PHP \DateTime object.
325  *
326  * @param \DateTime $datetime Source object.
327  *
328  * @return static
329  */
330  public static function createFromPhp(\DateTime $datetime)
331  {
332  /** @var Date $d */
333  $d = new static();
334  $d->value = clone $datetime;
335  $d->value->setTime(0, 0, 0);
336  return $d;
337  }
338 
339  /**
340  * Creates Date object from Unix timestamp.
341  *
342  * @param int $timestamp Source timestamp.
343  *
344  * @return static
345  */
346  public static function createFromTimestamp($timestamp)
347  {
348  /** @var Date $d */
349  $d = new static();
350  $d->value->setTimestamp($timestamp);
351  $d->value->setTime(0, 0, 0);
352  return $d;
353  }
354 
355  /**
356  * Creates Date object from Text (return array of result object)
357  * Examples: "end of next week", "tomorrow morning", "friday 25.10"
358  *
359  * @param string $text
360  * @return \Bitrix\Main\Type\DateTime|null
361  */
362  public static function createFromText($text)
363  {
364  $result = Main\Text\DateConverter::decode($text);
365  if (empty($result))
366  {
367  return null;
368  }
369 
370  return $result[0]->getDate();
371  }
372 }
Bitrix\Main\Type\Date\getDiff
getDiff(DateTime $time)
Returns difference between dates.
Definition: main/lib/type/date.php:179
Bitrix\Main\Type\Date\isCorrect
static isCorrect($time, $format=null)
Checks the string for correct date (by trying to create Date object).
Definition: main/lib/type/date.php:302
Bitrix\Main\Type\Date\__clone
__clone()
Produces the copy of the object.
Definition: main/lib/type/date.php:73
Bitrix\Main\ObjectException
Exception is thrown when the object can't be constructed.
Definition: main/lib/exception.php:191
Bitrix\Main
Bitrix\Main\Type\Date\toString
toString(Context\Culture $culture=null)
Converts a date to the string.
Definition: main/lib/type/date.php:191
Bitrix\Main\Type\Date\format
format($format)
Formats date value to string.
Definition: main/lib/type/date.php:63
Bitrix\Main\Type\Date\createFromTimestamp
static createFromTimestamp($timestamp)
Creates Date object from Unix timestamp.
Definition: main/lib/type/date.php:346
Bitrix\Main\Type\Date\getFormat
static getFormat(Context\Culture $culture=null)
Returns a date format from the culture in the php format.
Definition: main/lib/type/date.php:214
Bitrix\Main\Type
Definition: main/lib/type/collection.php:2
Bitrix\Main\Type\Date\createFromText
static createFromText($text)
Creates Date object from Text (return array of result object) Examples: "end of next week",...
Definition: main/lib/type/date.php:362
Bitrix\Main\Context
Context of current request.
Definition: main/lib/context.php:13
Bitrix\Main\Context\Culture
Definition: context/culture.php:13
Bitrix\Main\Type\Date\__construct
__construct($date=null, $format=null)
Definition: main/lib/type/date.php:18
Bitrix\Main\Text\DateConverter\decode
static decode($text, $limit=0)
Creates Date object from Text (return array of result object)
Definition: dateconverter.php:17
Bitrix\Main\Type\Date
Definition: main/lib/type/date.php:7
Bitrix\Main\Type\Date\__toString
__toString()
Converts a date to the string with default culture format setting.
Definition: main/lib/type/date.php:202
Bitrix\Main\Type\Date\add
add($interval)
Performs dates arithmetic.
Definition: main/lib/type/date.php:98
Bitrix\Main\Type\Date\getCultureFormat
static getCultureFormat(Context\Culture $culture)
Returns short date culture format.
Definition: main/lib/type/date.php:240
Bitrix\Main\Type\Date\createFromPhp
static createFromPhp(\DateTime $datetime)
Creates Date object from PHP \DateTime object.
Definition: main/lib/type/date.php:330
Bitrix\Main\Context
Definition: context/culture.php:9
Bitrix\Main\Type\Date\setDate
setDate($year, $month, $day)
Sets the current date of the DateTime object to a different date.
Definition: main/lib/type/date.php:119
Bitrix\Main\Type\DateTime\setTime
setTime($hour, $minute, $second=0, $microseconds=0)
Definition: main/lib/type/datetime.php:134
Bitrix\Main\Type\DateTime
Definition: main/lib/type/datetime.php:7
Bitrix\Main\Context\getCurrent
static getCurrent()
Static method returns current instance of context.
Definition: main/lib/context.php:194
Bitrix\Main\Type\Date\$value
$value
Definition: main/lib/type/date.php:10
Bitrix\Main\Type\Date\convertFormatToPhp
static convertFormatToPhp($format)
Converts date format from culture to php format.
Definition: main/lib/type/date.php:252
Bitrix\Main\Type\Date\getTimestamp
getTimestamp()
Returns Unix timestamp from date.
Definition: main/lib/type/date.php:168