1use jiff::{
4 SignedDuration, Timestamp, ZonedDateTime,
5 civil::{self, DateTime},
6 tz::{self, AmbiguousOffset, Disambiguation, Offset, TimeZone},
7};
8use std::{borrow::Cow, fmt};
9
10pub(crate) const EPOCH: DateTime = civil::datetime(1970, 1, 1, 0, 0, 0, 0);
12
13const ABBREVIATIONS: &[(&str, i32, bool)] = &[
18 ("Z", 0, false),
19 ("GMT", 0, false),
20 ("EST", -18_000, false),
21 ("EDT", -14_400, true),
22 ("CST", -21_600, false),
23 ("CDT", -18_000, true),
24 ("MST", -25_200, false),
25 ("MDT", -21_600, true),
26 ("PST", -28_800, false),
27 ("PDT", -25_200, true),
28 ("AKST", -32_400, false),
29 ("AKDT", -28_800, true),
30 ("HST", -36_000, false),
31 ("AST", -14_400, false),
32 ("ADT", -10_800, true),
33 ("NST", -12_600, false),
34 ("NDT", -9_000, true),
35 ("WET", 0, false),
36 ("WEST", 3_600, true),
37 ("BST", 3_600, true),
38 ("CET", 3_600, false),
39 ("CEST", 7_200, true),
40 ("EET", 7_200, false),
41 ("EEST", 10_800, true),
42 ("SAST", 7_200, false),
43 ("MSK", 10_800, false),
44 ("HKT", 28_800, false),
45 ("JST", 32_400, false),
46 ("KST", 32_400, false),
47 ("AWST", 28_800, false),
48 ("ACST", 34_200, false),
49 ("ACDT", 37_800, true),
50 ("AEST", 36_000, false),
51 ("AEDT", 39_600, true),
52 ("NZST", 43_200, false),
53 ("NZDT", 46_800, true),
54];
55
56#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum Zone {
62 Utc,
64 Offset(i32),
66 Abbreviation {
68 name: String,
70 offset: i32,
72 dst: bool,
74 },
75 Named(TimeZone),
78}
79
80impl Zone {
81 #[must_use]
88 pub fn parse(text: &str) -> Option<Self> {
89 let (zone, length) = Self::scan(text)?;
90 (length == text.len()).then_some(zone)
91 }
92
93 pub(crate) fn scan(text: &str) -> Option<(Self, usize)> {
95 let prefix = if text.starts_with("GMT+") || text.starts_with("GMT-") { 3 } else { 0 };
97 if let Some((offset, length)) = scan_offset(&text[prefix..]) {
98 return Some((Self::Offset(offset), prefix + length));
99 }
100 let length = text
101 .bytes()
102 .take_while(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'/' | b'+' | b'-'))
103 .count();
104 let word = &text[..length];
105 if word.is_empty() || not_an_identifier(word) {
106 return None;
107 }
108 if word.eq_ignore_ascii_case("UTC") {
109 return Some((Self::Utc, length));
110 }
111 if let Some(&(name, offset, dst)) = ABBREVIATIONS.iter().find(|(name, ..)| name.eq_ignore_ascii_case(word)) {
112 return Some((Self::Abbreviation { name: name.to_owned(), offset, dst }, length));
113 }
114 let zone = tz::db().get(word).ok()?;
115 zone.iana_name()?;
116 Some((Self::Named(zone), length))
117 }
118
119 fn time_zone(&self) -> Option<TimeZone> {
121 match self {
122 Self::Utc => Some(TimeZone::UTC),
123 Self::Offset(offset) | Self::Abbreviation { offset, .. } => {
124 Some(TimeZone::fixed(Offset::from_seconds(*offset).ok()?))
125 }
126 Self::Named(zone) => Some(zone.clone()),
127 }
128 }
129}
130
131fn not_an_identifier(word: &str) -> bool {
133 let lower = word.to_ascii_lowercase();
134 matches!(lower.as_str(), "posixrules" | "localtime" | "etc/unknown")
135 || ["posix/", "right/", "systemv/"].iter().any(|prefix| lower.starts_with(prefix))
136}
137
138impl From<TimeZone> for Zone {
139 fn from(zone: TimeZone) -> Self {
142 if zone == TimeZone::UTC {
143 return Self::Utc;
144 }
145 if zone.iana_name().is_some() {
146 return Self::Named(zone);
147 }
148 match zone.to_fixed_offset() {
149 Ok(offset) => Self::Offset(offset.seconds()),
150 Err(_) => Self::Named(zone),
151 }
152 }
153}
154
155fn scan_offset(text: &str) -> Option<(i32, usize)> {
158 let sign = match text.as_bytes().first()? {
159 b'+' => 1,
160 b'-' => -1,
161 _ => return None,
162 };
163 let run = text[1..].bytes().take_while(|byte| byte.is_ascii_digit() || *byte == b':').count();
164 let body = &text[1..=run];
165 let number = |part: &str| {
166 (!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())).then(|| part.parse::<i32>().ok()).flatten()
167 };
168 let (hours, minutes, seconds) = match (body.len(), body.find(':')) {
169 (1 | 2, None) => (number(body)?, 0, 0),
170 (2, Some(1)) => (number(&body[..1])?, 0, 0),
171 (3, Some(2)) => (number(&body[..2])?, 0, 0),
172 (3, None) => (number(&body[..1])?, number(&body[1..])?, 0),
173 (3, Some(1)) => (number(&body[..1])?, number(&body[2..])?, 0),
174 (4, None) => (number(&body[..2])?, number(&body[2..])?, 0),
175 (4, Some(1)) => (number(&body[..1])?, number(&body[2..])?, 0),
176 (4, Some(2)) => (number(&body[..2])?, number(&body[3..])?, 0),
177 (5, Some(2)) => (number(&body[..2])?, number(&body[3..])?, 0),
178 (6, None) => (number(&body[..2])?, number(&body[2..4])?, number(&body[4..])?),
179 (8, Some(2)) if body.as_bytes()[5] == b':' => (number(&body[..2])?, number(&body[3..5])?, number(&body[6..])?),
180 _ => return None,
181 };
182 if minutes > 59 || seconds > 59 {
183 return None;
184 }
185 let offset = sign * (hours * 3600 + minutes * 60 + seconds);
186 Offset::from_seconds(offset).ok()?;
187 Some((offset, 1 + run))
188}
189
190#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct PhpDateTime {
200 local: DateTime,
201 zone: Zone,
202 offset: i32,
203 dst: bool,
204 abbreviation: Cow<'static, str>,
205}
206
207impl PhpDateTime {
208 pub fn new(local: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
219 Self::new_with(local, zone, Disambiguation::Compatible)
220 }
221
222 pub fn new_with(local: DateTime, zone: Zone, disambiguation: Disambiguation) -> Result<Self, jiff::Error> {
228 match &zone {
229 Zone::Utc => Ok(local.into()),
230 Zone::Offset(offset) => {
231 let offset = *offset;
232 Offset::from_seconds(offset)?;
233 let mut abbreviation = String::from("GMT");
234 let _ = write_offset(&mut abbreviation, offset, "");
236 Ok(Self { local, offset, dst: false, abbreviation: abbreviation.into(), zone })
237 }
238 Zone::Abbreviation { name, offset, dst } => {
239 Offset::from_seconds(*offset)?;
240 let (offset, dst, abbreviation) = (*offset, *dst, Cow::Owned(name.clone()));
241 Ok(Self { local, offset, dst, abbreviation, zone })
242 }
243 Zone::Named(tz) => {
244 let (local, offset) = resolve(tz, local, disambiguation)?;
245 let offset = offset.seconds();
246 let info = tz.to_offset_info(clamped_instant(local, offset));
248 let (dst, abbreviation) = (info.dst().is_dst(), Cow::Owned(info.abbreviation().to_owned()));
249 Ok(Self { local, offset, dst, abbreviation, zone })
250 }
251 }
252 }
253
254 pub fn from_utc(utc: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
259 if let Ok(instant) = TimeZone::UTC.to_timestamp(utc) {
260 return Self::from_timestamp(instant, zone);
261 }
262 let offset = match &zone {
263 Zone::Utc => 0,
264 Zone::Offset(offset) | Zone::Abbreviation { offset, .. } => Offset::from_seconds(*offset)?.seconds(),
265 Zone::Named(tz) => tz.to_offset(clamped_instant(utc, 0)).seconds(),
266 };
267 Self::new(utc.checked_add(SignedDuration::from_secs(i64::from(offset)))?, zone)
268 }
269
270 pub fn from_timestamp(timestamp: Timestamp, zone: Zone) -> Result<Self, jiff::Error> {
275 match &zone {
276 Zone::Named(tz) => Ok(Self::from_zoned(×tamp.to_zoned_datetime(tz.clone()), zone)),
277 Zone::Utc => Self::new(TimeZone::UTC.to_datetime(timestamp), zone),
278 Zone::Offset(offset) | Zone::Abbreviation { offset, .. } => {
279 let local = TimeZone::fixed(Offset::from_seconds(*offset)?).to_datetime(timestamp);
280 Self::new(local, zone)
281 }
282 }
283 }
284
285 fn from_zoned(date: &ZonedDateTime, zone: Zone) -> Self {
286 let info = date.time_zone().to_offset_info(date.timestamp());
287 Self {
288 local: date.datetime(),
289 zone,
290 offset: info.offset().seconds(),
291 dst: info.dst().is_dst(),
292 abbreviation: Cow::Owned(info.abbreviation().to_owned()),
293 }
294 }
295
296 pub fn in_zone(&self, zone: Zone) -> Result<Self, jiff::Error> {
301 Self::from_utc(self.local.checked_sub(SignedDuration::from_secs(i64::from(self.offset)))?, zone)
302 }
303
304 #[must_use]
306 pub const fn datetime(&self) -> &DateTime {
307 &self.local
308 }
309
310 #[must_use]
312 pub const fn zone(&self) -> &Zone {
313 &self.zone
314 }
315
316 #[must_use]
318 pub const fn offset_seconds(&self) -> i32 {
319 self.offset
320 }
321
322 #[must_use]
324 pub const fn is_dst(&self) -> bool {
325 self.dst
326 }
327
328 #[must_use]
330 pub fn abbreviation(&self) -> &str {
331 &self.abbreviation
332 }
333
334 pub fn to_timestamp(&self) -> Result<Timestamp, jiff::Error> {
339 Timestamp::from_duration(since_epoch(self.local, self.offset))
340 }
341
342 #[must_use]
344 pub fn timestamp(&self) -> i64 {
345 let since = since_epoch(self.local, self.offset);
346 since.as_secs() - i64::from(since.subsec_nanos() < 0)
347 }
348
349 pub fn to_zoned_datetime(&self) -> Result<ZonedDateTime, jiff::Error> {
354 let zone = self.zone.time_zone().ok_or_else(|| jiff::Error::from_args(format_args!("invalid offset")))?;
355 Ok(self.to_timestamp()?.to_zoned_datetime(zone))
356 }
357}
358
359fn since_epoch(local: DateTime, offset: i32) -> SignedDuration {
361 local.duration_since(EPOCH) - SignedDuration::from_secs(i64::from(offset))
362}
363
364fn clamped_instant(local: DateTime, offset: i32) -> Timestamp {
366 Timestamp::from_duration(since_epoch(local, offset)).unwrap_or(if local.year() < 0 {
367 Timestamp::MIN
368 } else {
369 Timestamp::MAX
370 })
371}
372
373fn resolve(
376 zone: &TimeZone,
377 local: DateTime,
378 disambiguation: Disambiguation,
379) -> Result<(DateTime, Offset), jiff::Error> {
380 let rejected = |what| jiff::Error::from_args(format_args!("the local time {local} is {what} in this time zone"));
381 let gap = |before: Offset, after: Offset| SignedDuration::from_secs(i64::from(after.seconds() - before.seconds()));
382 Ok(match zone.to_ambiguous_timestamp(local).offset() {
383 AmbiguousOffset::Unambiguous { offset } => (local, offset),
384 AmbiguousOffset::Gap { before, after } => match disambiguation {
385 Disambiguation::Compatible | Disambiguation::Later => (local.checked_add(gap(before, after))?, after),
386 Disambiguation::Earlier => (local.checked_sub(gap(before, after))?, before),
387 _ => return Err(rejected("skipped")),
388 },
389 AmbiguousOffset::Fold { before, after } => match disambiguation {
390 Disambiguation::Compatible | Disambiguation::Earlier => (local, before),
391 Disambiguation::Later => (local, after),
392 _ => return Err(rejected("repeated")),
393 },
394 })
395}
396
397pub(crate) fn write_offset<W: fmt::Write + ?Sized>(out: &mut W, offset: i32, separator: &str) -> fmt::Result {
399 let sign = if offset < 0 { '-' } else { '+' };
400 let seconds = offset.unsigned_abs();
401 write!(out, "{sign}{:02}{separator}{:02}", seconds / 3600, seconds % 3600 / 60)
402}
403
404impl From<&Self> for PhpDateTime {
405 fn from(date: &Self) -> Self {
406 date.clone()
407 }
408}
409
410impl From<DateTime> for PhpDateTime {
411 fn from(local: DateTime) -> Self {
413 Self { local, zone: Zone::Utc, offset: 0, dst: false, abbreviation: Cow::Borrowed("UTC") }
414 }
415}
416
417impl From<&DateTime> for PhpDateTime {
418 fn from(local: &DateTime) -> Self {
420 (*local).into()
421 }
422}
423
424impl From<Timestamp> for PhpDateTime {
425 fn from(timestamp: Timestamp) -> Self {
426 TimeZone::UTC.to_datetime(timestamp).into()
427 }
428}
429
430impl From<ZonedDateTime> for PhpDateTime {
431 fn from(date: ZonedDateTime) -> Self {
433 Self::from_zoned(&date, date.time_zone().clone().into())
434 }
435}