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::{self, DateTime},
6    tz::{self, AmbiguousOffset, Disambiguation, Offset, TimeZone},
7};
8use std::{borrow::Cow, fmt};
9
10/// The start of Unix time, as a wall-clock time.
11pub(crate) const EPOCH: DateTime = civil::datetime(1970, 1, 1, 0, 0, 0, 0);
12
13/// Zone abbreviations understood by `T`, `e`, `O`, `P` and `p`: name, seconds east of UTC, daylight saving.
14///
15/// PHP's own table is much longer, and takes the oldest meaning of some names: `KST` is `+08:30` there and `NDT` is
16/// `-02:30:52`. Here they are the offsets in use today.
17const 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/// A time zone, in the three forms PHP has: an identifier, an abbreviation and a fixed offset.
57///
58/// The variants are open so that they can be matched. When building one by hand, prefer [`Zone::parse`] or the
59/// `From<jiff::tz::TimeZone>` conversion: an offset out of range is only reported when a [`PhpDateTime`] is built.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum Zone {
62    /// `UTC`.
63    Utc,
64    /// A fixed offset, in seconds east of UTC: `+02:00`. Jiff accepts up to `±25:59:59`.
65    Offset(i32),
66    /// An abbreviation: `EST`, `CEST`, `Z`.
67    Abbreviation {
68        /// The abbreviation, in capitals.
69        name: String,
70        /// Seconds east of UTC.
71        offset: i32,
72        /// Whether it is a daylight saving abbreviation.
73        dst: bool,
74    },
75    /// A zone with its own rules: an IANA identifier such as `Europe/Madrid`. A jiff zone that has rules but no name
76    /// (a POSIX `TZ` string, some system zones) is kept here too, and `e` prints its offset.
77    Named(TimeZone),
78}
79
80impl Zone {
81    /// Read a zone the way `new DateTimeZone($text)` does: an identifier (`Europe/Madrid`, in any letter case), an
82    /// abbreviation (`EST`, `CEST`, a short list) or an offset (`+02:00`, `+0200`, `+02`, `GMT+2`, with `GMT` in
83    /// capitals). Files of the time zone database that PHP does not take as identifiers (`posixrules`, `localtime`,
84    /// `posix/...`, `right/...`, `SystemV/...`) are rejected.
85    ///
86    /// Returns `None` when `text` is not entirely a zone.
87    #[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    /// The zone at the start of `text` and how many bytes it takes.
94    pub(crate) fn scan(text: &str) -> Option<(Self, usize)> {
95        // PHP skips `GMT`, in capitals, before a sign; `gmt+2` and `UTC+2` are not zones.
96        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    /// The jiff zone to compute with.
120    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
131/// Names jiff resolves from the files of a system's database that PHP does not take as identifiers.
132fn 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    /// `UTC` for jiff's UTC, [`Zone::Offset`] for an unnamed fixed offset and [`Zone::Named`] for a zone with a name
140    /// or with rules of its own.
141    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
155/// An offset the way PHP reads it. Every digit and `:` after the sign belongs to it, and the whole run must be one of
156/// `H`, `HH`, `H:`, `HH:`, `H:M`, `HMM`, `H:MM`, `HH:M`, `HHMM`, `HH:MM`, `HHMMSS` or `HH:MM:SS`.
157fn 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/// A date and time with its time zone: what `DateTime::format()` prints and `createFromFormat()` returns.
191///
192/// Build one from a jiff `civil::DateTime` (read as UTC), a `Timestamp` (UTC), a `ZonedDateTime`, or with
193/// [`PhpDateTime::new`].
194///
195/// It covers every wall-clock time jiff's `civil::DateTime` does (years `-9999` to `9999`), which is a little more than
196/// its `Timestamp`: at both ends [`timestamp`](Self::timestamp) still answers, and
197/// [`to_timestamp`](Self::to_timestamp) is an error.
198#[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    /// A wall-clock time in `zone`. A time that does not exist there (the hour a daylight saving change skips)
209    /// moves forward, as PHP moves it, and a time that happens twice is the first one
210    /// ([`Disambiguation::Compatible`]).
211    ///
212    /// PHP does not always take the first one: for `new DateTime($time, $zone)` and for a `createFromFormat()` value
213    /// that names no zone, it takes the second when the clocks go back to UTC+0 or ahead of it, as in `Europe/London`,
214    /// `Europe/Madrid` or `Australia/Sydney`. Use [`new_with`](Self::new_with) to choose.
215    ///
216    /// # Errors
217    /// For an offset out of range, or when a skipped hour moves past the last date jiff supports.
218    pub fn new(local: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
219        Self::new_with(local, zone, Disambiguation::Compatible)
220    }
221
222    /// [`new`](Self::new), choosing what happens with a wall-clock time that a [`Zone::Named`] skips or repeats.
223    /// The other zones have a single offset, so `disambiguation` changes nothing for them.
224    ///
225    /// # Errors
226    /// Those of [`new`](Self::new), and [`Disambiguation::Reject`] for a skipped or repeated time.
227    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                // Writing to a `String` cannot fail.
235                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                // Past the ends of `Timestamp` there are no more transitions: the rules at the end still hold.
247                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    /// The instant `utc` (a UTC wall-clock time) seen from `zone`.
255    ///
256    /// # Errors
257    /// For an offset out of range, or a result outside the dates jiff supports.
258    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    /// The instant `timestamp` seen from `zone`.
271    ///
272    /// # Errors
273    /// For an offset out of range.
274    pub fn from_timestamp(timestamp: Timestamp, zone: Zone) -> Result<Self, jiff::Error> {
275        match &zone {
276            Zone::Named(tz) => Ok(Self::from_zoned(&timestamp.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    /// The same instant in another zone.
297    ///
298    /// # Errors
299    /// For an offset out of range, or a result outside the dates jiff supports.
300    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    /// The wall-clock time, without the zone.
305    #[must_use]
306    pub const fn datetime(&self) -> &DateTime {
307        &self.local
308    }
309
310    /// The zone.
311    #[must_use]
312    pub const fn zone(&self) -> &Zone {
313        &self.zone
314    }
315
316    /// Seconds east of UTC at this instant (`Z`).
317    #[must_use]
318    pub const fn offset_seconds(&self) -> i32 {
319        self.offset
320    }
321
322    /// Whether daylight saving time is in effect (`I`).
323    #[must_use]
324    pub const fn is_dst(&self) -> bool {
325        self.dst
326    }
327
328    /// The zone abbreviation at this instant, as `T` prints it.
329    #[must_use]
330    pub fn abbreviation(&self) -> &str {
331        &self.abbreviation
332    }
333
334    /// The instant.
335    ///
336    /// # Errors
337    /// When the instant falls outside the range of jiff's `Timestamp`.
338    pub fn to_timestamp(&self) -> Result<Timestamp, jiff::Error> {
339        Timestamp::from_duration(since_epoch(self.local, self.offset))
340    }
341
342    /// The Unix timestamp (`U`): whole seconds, rounded down as PHP does, so half a second before 1970 is `-1`.
343    #[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    /// The instant as a jiff `ZonedDateTime`.
350    ///
351    /// # Errors
352    /// When the instant falls outside the range of jiff's `Timestamp`.
353    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
359/// The time from the epoch to the wall-clock time `local` seen at `offset`, over the whole range of `civil::DateTime`.
360fn since_epoch(local: DateTime, offset: i32) -> SignedDuration {
361    local.duration_since(EPOCH) - SignedDuration::from_secs(i64::from(offset))
362}
363
364/// The instant of `local` at `offset`, or the nearest one jiff has.
365fn 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
373/// The wall-clock time and offset of `local` in `zone`. Unlike jiff's own disambiguation it does not need the instant,
374/// so it also answers at the ends of the calendar.
375fn 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
397/// `+0530` with an empty `separator`, `+05:30` with `:`.
398pub(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    /// Read as UTC.
412    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    /// Read as UTC.
419    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    /// The wall-clock time, offset and zone of `date`.
432    fn from(date: ZonedDateTime) -> Self {
433        Self::from_zoned(&date, date.time_zone().clone().into())
434    }
435}