-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathTimeZone.php
More file actions
99 lines (82 loc) · 2.67 KB
/
TimeZone.php
File metadata and controls
99 lines (82 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
declare(strict_types=1);
namespace Brick\DateTime;
use Brick\DateTime\Parser\DateTimeParseException;
use DateTimeImmutable;
use DateTimeZone;
use Stringable;
use const PHP_VERSION_ID;
/**
* A time-zone. This is the parent class for `TimeZoneOffset` and `TimeZoneRegion`.
*
* * `TimeZoneOffset` represents a fixed offset from UTC such as `+02:00`.
* * `TimeZoneRegion` represents a geographical region such as `Europe/London`.
*/
abstract class TimeZone implements Stringable
{
/**
* Obtains an instance of `TimeZone` from a string representation.
*
* @throws DateTimeParseException
*/
public static function parse(string $text): TimeZone
{
if ($text === 'Z' || $text === 'z') {
return TimeZoneOffset::utc();
}
if ($text === '') {
throw new DateTimeParseException('The string is empty.');
}
if ($text[0] === '+' || $text[0] === '-') {
return TimeZoneOffset::parse($text);
}
return TimeZoneRegion::parse($text);
}
/**
* Returns the unique time-zone ID.
*
* @psalm-return non-empty-string
*/
abstract public function getId(): string;
/**
* Returns the offset from UTC at the given instant.
*
* @param Instant $pointInTime The instant.
*
* @return int The offset from UTC in seconds.
*/
abstract public function getOffset(Instant $pointInTime): int;
public function isEqualTo(TimeZone $other): bool
{
return $this->getId() === $other->getId();
}
public static function fromNativeDateTimeZone(DateTimeZone $dateTimeZone): TimeZone
{
$parsed = TimeZone::parse($dateTimeZone->getName());
/**
* PHP >= 8.1.7 supports sub-minute offsets, but truncates the seconds in getName(). Only getOffset() returns
* the correct offset including seconds, so let's use it to make a correction if we have an offset-based TZ.
* This has been fixed in PHP 8.1.20 and PHP 8.2.7.
*/
if ($parsed instanceof TimeZoneOffset
&& (
(PHP_VERSION_ID >= 8_01_07 && PHP_VERSION_ID < 8_01_20)
|| (PHP_VERSION_ID >= 8_02_00 && PHP_VERSION_ID < 8_02_07)
)
) {
return TimeZoneOffset::ofTotalSeconds($dateTimeZone->getOffset(new DateTimeImmutable()));
}
return $parsed;
}
/**
* Returns an equivalent native `DateTimeZone` object for this TimeZone.
*/
abstract public function toNativeDateTimeZone(): DateTimeZone;
/**
* @psalm-return non-empty-string
*/
public function __toString(): string
{
return $this->getId();
}
}