Skip to main content

php_dates/
zone.rs

1//! Time zones and the date-time `format()` reads: PHP's three kinds of zone.
2
3use jiff::{
4    SignedDuration, Timestamp, ZonedDateTime,
5    civil::DateTime,
6    tz::{self, Offset, TimeZone},
7};
8
9/// Zone abbreviations understood by `T`, `e`, `O`, `P` and `p`: name, seconds east of UTC, daylight saving.
10const 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/// A time zone, in the three forms PHP has: an identifier, an abbreviation and a fixed offset.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum Zone {
52    /// `UTC`.
53    Utc,
54    /// A fixed offset, in seconds east of UTC: `+02:00`. Jiff accepts up to `±25:59:59`.
55    Offset(i32),
56    /// An abbreviation: `EST`, `CEST`, `Z`.
57    Abbreviation {
58        /// The abbreviation, in capitals.
59        name: String,
60        /// Seconds east of UTC.
61        offset: i32,
62        /// Whether it is a daylight saving abbreviation.
63        dst: bool,
64    },
65    /// An IANA identifier: `Europe/Madrid`.
66    Named(TimeZone),
67}
68
69impl Zone {
70    /// Read a zone the way `new DateTimeZone($text)` does: an identifier (`Europe/Madrid`, in any letter case), an
71    /// abbreviation (`EST`, `CEST`, a short list) or an offset (`+02:00`, `+0200`, `+02`, `GMT+2`).
72    ///
73    /// Returns `None` when `text` is not entirely a zone.
74    #[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    /// The zone at the start of `text` and how many bytes it takes.
81    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    /// The jiff zone to compute with.
109    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    /// `UTC` for jiff's UTC, an identifier for a zone with a name and a fixed offset for one without.
122    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
133/// An offset the way PHP reads it. Every digit and `:` after the sign belongs to it, and the whole run must be one of
134/// `H`, `HH`, `H:M`, `HMM`, `H:MM`, `HH:M`, `HHMM`, `HH:MM`, `HHMMSS` or `HH:MM:SS`.
135fn 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/// A date and time with its time zone: what `DateTime::format()` prints and `createFromFormat()` returns.
167///
168/// Build one from a jiff `civil::DateTime` (read as UTC), a `Timestamp` (UTC), a `ZonedDateTime`, or with
169/// [`PhpDateTime::new`].
170#[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    /// A wall-clock time in `zone`. A time that does not exist there (the hour a daylight saving change skips)
181    /// moves forward as PHP moves it, and a time that happens twice is the first one.
182    ///
183    /// # Errors
184    /// When the result falls outside the dates jiff supports (years `-9999` to `9999`).
185    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    /// The instant `utc` (a UTC wall-clock time) seen from `zone`.
207    ///
208    /// # Errors
209    /// When the result falls outside the dates jiff supports.
210    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    /// The instant `timestamp` seen from `zone`.
216    ///
217    /// # Errors
218    /// When the result falls outside the dates jiff supports.
219    pub fn from_timestamp(timestamp: Timestamp, zone: Zone) -> Result<Self, jiff::Error> {
220        match &zone {
221            Zone::Named(tz) => Ok(Self::from_zoned(&timestamp.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    /// The same instant in another zone.
242    ///
243    /// # Errors
244    /// When the result falls outside the dates jiff supports.
245    pub fn in_zone(&self, zone: Zone) -> Result<Self, jiff::Error> {
246        Self::from_timestamp(self.to_timestamp()?, zone)
247    }
248
249    /// The wall-clock time, without the zone.
250    #[must_use]
251    pub const fn datetime(&self) -> &DateTime {
252        &self.local
253    }
254
255    /// The zone.
256    #[must_use]
257    pub const fn zone(&self) -> &Zone {
258        &self.zone
259    }
260
261    /// Seconds east of UTC at this instant (`Z`).
262    #[must_use]
263    pub const fn offset_seconds(&self) -> i32 {
264        self.offset
265    }
266
267    /// Whether daylight saving time is in effect (`I`).
268    #[must_use]
269    pub const fn is_dst(&self) -> bool {
270        self.dst
271    }
272
273    /// The instant.
274    ///
275    /// # Errors
276    /// When the instant falls outside the range jiff supports.
277    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    /// The Unix timestamp (`U`), saturating at the ends of jiff's range.
282    #[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    /// The instant as a jiff `ZonedDateTime`.
291    ///
292    /// # Errors
293    /// When the instant falls outside the range jiff supports.
294    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    /// The abbreviation `T` prints.
300    pub(crate) fn abbreviation(&self) -> &str {
301        &self.abbreviation
302    }
303}
304
305/// `+0530`
306pub(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    /// Read as UTC.
319    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    /// Read as UTC.
326    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}