1use jiff::{
4 SignedDuration, Timestamp, ZonedDateTime,
5 civil::DateTime,
6 tz::{self, Offset, TimeZone},
7};
8
9const ABBREVIATIONS: &[(&str, i32, bool)] = &[
11 ("Z", 0, false),
12 ("GMT", 0, false),
13 ("EST", -18_000, false),
14 ("EDT", -14_400, true),
15 ("CST", -21_600, false),
16 ("CDT", -18_000, true),
17 ("MST", -25_200, false),
18 ("MDT", -21_600, true),
19 ("PST", -28_800, false),
20 ("PDT", -25_200, true),
21 ("AKST", -32_400, false),
22 ("AKDT", -28_800, true),
23 ("HST", -36_000, false),
24 ("AST", -14_400, false),
25 ("ADT", -10_800, true),
26 ("NST", -12_600, false),
27 ("NDT", -9_000, true),
28 ("WET", 0, false),
29 ("WEST", 3_600, true),
30 ("BST", 3_600, true),
31 ("CET", 3_600, false),
32 ("CEST", 7_200, true),
33 ("EET", 7_200, false),
34 ("EEST", 10_800, true),
35 ("SAST", 7_200, false),
36 ("MSK", 10_800, false),
37 ("HKT", 28_800, false),
38 ("JST", 32_400, false),
39 ("KST", 32_400, false),
40 ("AWST", 28_800, false),
41 ("ACST", 34_200, false),
42 ("ACDT", 37_800, true),
43 ("AEST", 36_000, false),
44 ("AEDT", 39_600, true),
45 ("NZST", 43_200, false),
46 ("NZDT", 46_800, true),
47];
48
49#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum Zone {
52 Utc,
54 Offset(i32),
56 Abbreviation {
58 name: String,
60 offset: i32,
62 dst: bool,
64 },
65 Named(TimeZone),
67}
68
69impl Zone {
70 #[must_use]
75 pub fn parse(text: &str) -> Option<Self> {
76 let (zone, length) = Self::scan(text)?;
77 (length == text.len()).then_some(zone)
78 }
79
80 pub(crate) fn scan(text: &str) -> Option<(Self, usize)> {
82 let prefix = ["GMT", "UTC"]
83 .iter()
84 .find(|prefix| text.get(..3).is_some_and(|head| head.eq_ignore_ascii_case(prefix)))
85 .map_or(0, |_| 3);
86 if let Some((offset, length)) = scan_offset(&text[prefix..]) {
87 return Some((Self::Offset(offset), prefix + length));
88 }
89 let length = text
90 .bytes()
91 .take_while(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'/' | b'+' | b'-'))
92 .count();
93 let word = &text[..length];
94 if word.is_empty() {
95 return None;
96 }
97 if word.eq_ignore_ascii_case("UTC") {
98 return Some((Self::Utc, length));
99 }
100 if let Some(&(name, offset, dst)) = ABBREVIATIONS.iter().find(|(name, ..)| name.eq_ignore_ascii_case(word)) {
101 return Some((Self::Abbreviation { name: name.to_owned(), offset, dst }, length));
102 }
103 let zone = tz::db().get(word).ok()?;
104 zone.iana_name()?;
105 Some((Self::Named(zone), length))
106 }
107
108 fn time_zone(&self) -> Option<TimeZone> {
110 match self {
111 Self::Utc => Some(TimeZone::UTC),
112 Self::Offset(offset) | Self::Abbreviation { offset, .. } => {
113 Some(TimeZone::fixed(Offset::from_seconds(*offset).ok()?))
114 }
115 Self::Named(zone) => Some(zone.clone()),
116 }
117 }
118}
119
120impl From<TimeZone> for Zone {
121 fn from(zone: TimeZone) -> Self {
123 if zone == TimeZone::UTC {
124 return Self::Utc;
125 }
126 match zone.iana_name() {
127 Some(_) => Self::Named(zone),
128 None => Self::Offset(zone.to_offset(Timestamp::UNIX_EPOCH).seconds()),
129 }
130 }
131}
132
133fn scan_offset(text: &str) -> Option<(i32, usize)> {
136 let sign = match text.as_bytes().first()? {
137 b'+' => 1,
138 b'-' => -1,
139 _ => return None,
140 };
141 let run = text[1..].bytes().take_while(|byte| byte.is_ascii_digit() || *byte == b':').count();
142 let body = &text[1..=run];
143 let number = |part: &str| (!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())).then(|| part.parse::<i32>().ok()).flatten();
144 let (hours, minutes, seconds) = match (body.len(), body.find(':')) {
145 (1 | 2, None) => (number(body)?, 0, 0),
146 (3, None) => (number(&body[..1])?, number(&body[1..])?, 0),
147 (3, Some(1)) => (number(&body[..1])?, number(&body[2..])?, 0),
148 (4, None) => (number(&body[..2])?, number(&body[2..])?, 0),
149 (4, Some(1)) => (number(&body[..1])?, number(&body[2..])?, 0),
150 (4, Some(2)) => (number(&body[..2])?, number(&body[3..])?, 0),
151 (5, Some(2)) => (number(&body[..2])?, number(&body[3..])?, 0),
152 (6, None) => (number(&body[..2])?, number(&body[2..4])?, number(&body[4..])?),
153 (8, Some(2)) if body.as_bytes()[5] == b':' => {
154 (number(&body[..2])?, number(&body[3..5])?, number(&body[6..])?)
155 }
156 _ => return None,
157 };
158 if minutes > 59 || seconds > 59 {
159 return None;
160 }
161 let offset = sign * (hours * 3600 + minutes * 60 + seconds);
162 Offset::from_seconds(offset).ok()?;
163 Some((offset, 1 + run))
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct PhpDateTime {
172 local: DateTime,
173 zone: Zone,
174 offset: i32,
175 dst: bool,
176 abbreviation: String,
177}
178
179impl PhpDateTime {
180 pub fn new(local: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
186 match &zone {
187 Zone::Utc => Ok(Self { local, offset: 0, dst: false, abbreviation: "UTC".into(), zone }),
188 Zone::Offset(offset) => {
189 let offset = *offset;
190 Offset::from_seconds(offset)?;
191 let abbreviation = format!("GMT{}", compact_offset(offset));
192 Ok(Self { local, offset, dst: false, abbreviation, zone })
193 }
194 Zone::Abbreviation { name, offset, dst } => {
195 Offset::from_seconds(*offset)?;
196 let (offset, dst, abbreviation) = (*offset, *dst, name.clone());
197 Ok(Self { local, offset, dst, abbreviation, zone })
198 }
199 Zone::Named(tz) => {
200 let zoned = tz.to_ambiguous_zoned_datetime(local).compatible()?;
201 Ok(Self::from_zoned(&zoned, zone))
202 }
203 }
204 }
205
206 pub fn from_utc(utc: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
211 let instant = TimeZone::UTC.to_timestamp(utc)?;
212 Self::from_timestamp(instant, zone)
213 }
214
215 pub fn from_timestamp(timestamp: Timestamp, zone: Zone) -> Result<Self, jiff::Error> {
220 match &zone {
221 Zone::Named(tz) => Ok(Self::from_zoned(×tamp.to_zoned_datetime(tz.clone()), zone)),
222 Zone::Utc => Self::new(TimeZone::UTC.to_datetime(timestamp), zone),
223 Zone::Offset(offset) | Zone::Abbreviation { offset, .. } => {
224 let local = TimeZone::fixed(Offset::from_seconds(*offset)?).to_datetime(timestamp);
225 Self::new(local, zone)
226 }
227 }
228 }
229
230 fn from_zoned(date: &ZonedDateTime, zone: Zone) -> Self {
231 let info = date.time_zone().to_offset_info(date.timestamp());
232 Self {
233 local: date.datetime(),
234 zone,
235 offset: info.offset().seconds(),
236 dst: info.dst().is_dst(),
237 abbreviation: info.abbreviation().to_owned(),
238 }
239 }
240
241 pub fn in_zone(&self, zone: Zone) -> Result<Self, jiff::Error> {
246 Self::from_timestamp(self.to_timestamp()?, zone)
247 }
248
249 #[must_use]
251 pub const fn datetime(&self) -> &DateTime {
252 &self.local
253 }
254
255 #[must_use]
257 pub const fn zone(&self) -> &Zone {
258 &self.zone
259 }
260
261 #[must_use]
263 pub const fn offset_seconds(&self) -> i32 {
264 self.offset
265 }
266
267 #[must_use]
269 pub const fn is_dst(&self) -> bool {
270 self.dst
271 }
272
273 pub fn to_timestamp(&self) -> Result<Timestamp, jiff::Error> {
278 TimeZone::UTC.to_timestamp(self.local)?.checked_sub(SignedDuration::from_secs(i64::from(self.offset)))
279 }
280
281 #[must_use]
283 pub fn timestamp(&self) -> i64 {
284 self.to_timestamp().map_or_else(
285 |_| if self.local.year() < 0 { Timestamp::MIN.as_second() } else { Timestamp::MAX.as_second() },
286 |timestamp| timestamp.as_second(),
287 )
288 }
289
290 pub fn to_zoned_datetime(&self) -> Result<ZonedDateTime, jiff::Error> {
295 let zone = self.zone.time_zone().ok_or_else(|| jiff::Error::from_args(format_args!("invalid offset")))?;
296 Ok(self.to_timestamp()?.to_zoned_datetime(zone))
297 }
298
299 pub(crate) fn abbreviation(&self) -> &str {
301 &self.abbreviation
302 }
303}
304
305pub(crate) fn compact_offset(offset: i32) -> String {
307 let sign = if offset < 0 { '-' } else { '+' };
308 format!("{sign}{:02}{:02}", offset.abs() / 3600, offset.abs() % 3600 / 60)
309}
310
311impl From<&Self> for PhpDateTime {
312 fn from(date: &Self) -> Self {
313 date.clone()
314 }
315}
316
317impl From<DateTime> for PhpDateTime {
318 fn from(local: DateTime) -> Self {
320 Self { local, zone: Zone::Utc, offset: 0, dst: false, abbreviation: "UTC".into() }
321 }
322}
323
324impl From<&DateTime> for PhpDateTime {
325 fn from(local: &DateTime) -> Self {
327 (*local).into()
328 }
329}
330
331impl From<Timestamp> for PhpDateTime {
332 fn from(timestamp: Timestamp) -> Self {
333 TimeZone::UTC.to_datetime(timestamp).into()
334 }
335}
336
337impl From<ZonedDateTime> for PhpDateTime {
338 fn from(date: ZonedDateTime) -> Self {
339 Self::from_zoned(&date, date.time_zone().clone().into())
340 }
341}