Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
date.php
1<?php
2
4
6
7class Date implements \JsonSerializable
8{
9 protected $timestamp;
10 protected $offset;
11
12 const SERIALIZED_PATTERN = '#(.+)\s\[([0-9\-]+)\]#i';
13
14 public function __construct($dateFormatted = null, $offset = 0)
15 {
16 $offset = (int) $offset;
17
18 if ($dateFormatted === null)
19 {
20 $this->timestamp = (new Main\Type\Date())->getTimestamp();
21 }
22 elseif (is_numeric($dateFormatted))
23 {
24 $this->timestamp = (int) $dateFormatted;
25 }
26 else
27 {
28 if (preg_match(static::SERIALIZED_PATTERN, $dateFormatted, $matches))
29 {
30 $dateFormatted = $matches[1];
31 $offset = (int) $matches[2];
32 }
33
34 try
35 {
36 $date = new Main\Type\Date($dateFormatted);
37 $this->checkYear($date);
38
39 $this->timestamp = $date->getTimestamp() - $offset;
40 }
41 catch (Main\ObjectException $exception)
42 {
43 try
44 {
45 $this->timestamp = (new Main\Type\Date($dateFormatted, DATE_ISO8601))->getTimestamp() - $offset;
46 }
47 catch (Main\ObjectException $exception)
48 {
49 $this->timestamp = null;
50 }
51 }
52 }
53
54 $this->offset = $offset;
55 }
56
57 public function getTimestamp()
58 {
59 return $this->timestamp;
60 }
61
62 public function getOffset()
63 {
64 return $this->offset;
65 }
66
67 public function __toString()
68 {
69 return date($this->getFormat(), $this->getTimestamp() + $this->offset);
70 }
71
72 public static function fromSystemObject(Main\Type\Date $date)
73 {
74 return new static($date->getTimestamp());
75 }
76
77 public function toSystemObject()
78 {
79 return Main\Type\Date::createFromTimestamp($this->getTimestamp() + $this->offset);
80 }
81
82 public function serialize()
83 {
84 return sprintf('%s [%d]', $this->__toString(), $this->offset);
85 }
86
87 public static function isSerialized($dateString)
88 {
89 if (is_string($dateString) && preg_match(static::SERIALIZED_PATTERN, $dateString))
90 {
91 return true;
92 }
93 return false;
94 }
95
96 public function getFormat()
97 {
98 return Main\Type\Date::getFormat();
99 }
100
101 protected function checkYear(Main\Type\Date $date)
102 {
103 if ($date->getTimestamp() < 0)
104 {
105 $y = (int) $date->format('Y');
106 $m = (int) $date->format('m');
107 $d = (int) $date->format('d');
108 if (0 <= $y && $y <= 69)
109 {
110 $y += 2000;
111 $date->setDate($y, $m, $d);
112 }
113 elseif (70 <= $y && $y <= 100)
114 {
115 $y += 1900;
116 $date->setDate($y, $m, $d);
117 }
118 }
119 }
120
121 public function jsonSerialize()
122 {
123 return $this->serialize();
124 }
125}
checkYear(Main\Type\Date $date)
Definition date.php:101
static isSerialized($dateString)
Definition date.php:87
static fromSystemObject(Main\Type\Date $date)
Definition date.php:72
__construct($dateFormatted=null, $offset=0)
Definition date.php:14