php-dates 0.2.0

PHP date() patterns for Rust: strict createFromFormat-style parsing, a pattern resolution contract and a Day.js export, with no framework dependency
Documentation
//! Time zones and the date-time `format()` reads: PHP's three kinds of zone.

use jiff::{
    SignedDuration, Timestamp, ZonedDateTime,
    civil::DateTime,
    tz::{self, Offset, TimeZone},
};

/// Zone abbreviations understood by `T`, `e`, `O`, `P` and `p`: name, seconds east of UTC, daylight saving.
const ABBREVIATIONS: &[(&str, i32, bool)] = &[
    ("Z", 0, false),
    ("GMT", 0, false),
    ("EST", -18_000, false),
    ("EDT", -14_400, true),
    ("CST", -21_600, false),
    ("CDT", -18_000, true),
    ("MST", -25_200, false),
    ("MDT", -21_600, true),
    ("PST", -28_800, false),
    ("PDT", -25_200, true),
    ("AKST", -32_400, false),
    ("AKDT", -28_800, true),
    ("HST", -36_000, false),
    ("AST", -14_400, false),
    ("ADT", -10_800, true),
    ("NST", -12_600, false),
    ("NDT", -9_000, true),
    ("WET", 0, false),
    ("WEST", 3_600, true),
    ("BST", 3_600, true),
    ("CET", 3_600, false),
    ("CEST", 7_200, true),
    ("EET", 7_200, false),
    ("EEST", 10_800, true),
    ("SAST", 7_200, false),
    ("MSK", 10_800, false),
    ("HKT", 28_800, false),
    ("JST", 32_400, false),
    ("KST", 32_400, false),
    ("AWST", 28_800, false),
    ("ACST", 34_200, false),
    ("ACDT", 37_800, true),
    ("AEST", 36_000, false),
    ("AEDT", 39_600, true),
    ("NZST", 43_200, false),
    ("NZDT", 46_800, true),
];

/// A time zone, in the three forms PHP has: an identifier, an abbreviation and a fixed offset.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Zone {
    /// `UTC`.
    Utc,
    /// A fixed offset, in seconds east of UTC: `+02:00`. Jiff accepts up to `±25:59:59`.
    Offset(i32),
    /// An abbreviation: `EST`, `CEST`, `Z`.
    Abbreviation {
        /// The abbreviation, in capitals.
        name: String,
        /// Seconds east of UTC.
        offset: i32,
        /// Whether it is a daylight saving abbreviation.
        dst: bool,
    },
    /// An IANA identifier: `Europe/Madrid`.
    Named(TimeZone),
}

impl Zone {
    /// Read a zone the way `new DateTimeZone($text)` does: an identifier (`Europe/Madrid`, in any letter case), an
    /// abbreviation (`EST`, `CEST`, a short list) or an offset (`+02:00`, `+0200`, `+02`, `GMT+2`).
    ///
    /// Returns `None` when `text` is not entirely a zone.
    #[must_use]
    pub fn parse(text: &str) -> Option<Self> {
        let (zone, length) = Self::scan(text)?;
        (length == text.len()).then_some(zone)
    }

    /// The zone at the start of `text` and how many bytes it takes.
    pub(crate) fn scan(text: &str) -> Option<(Self, usize)> {
        let prefix = ["GMT", "UTC"]
            .iter()
            .find(|prefix| text.get(..3).is_some_and(|head| head.eq_ignore_ascii_case(prefix)))
            .map_or(0, |_| 3);
        if let Some((offset, length)) = scan_offset(&text[prefix..]) {
            return Some((Self::Offset(offset), prefix + length));
        }
        let length = text
            .bytes()
            .take_while(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'/' | b'+' | b'-'))
            .count();
        let word = &text[..length];
        if word.is_empty() {
            return None;
        }
        if word.eq_ignore_ascii_case("UTC") {
            return Some((Self::Utc, length));
        }
        if let Some(&(name, offset, dst)) = ABBREVIATIONS.iter().find(|(name, ..)| name.eq_ignore_ascii_case(word)) {
            return Some((Self::Abbreviation { name: name.to_owned(), offset, dst }, length));
        }
        let zone = tz::db().get(word).ok()?;
        zone.iana_name()?;
        Some((Self::Named(zone), length))
    }

    /// The jiff zone to compute with.
    fn time_zone(&self) -> Option<TimeZone> {
        match self {
            Self::Utc => Some(TimeZone::UTC),
            Self::Offset(offset) | Self::Abbreviation { offset, .. } => {
                Some(TimeZone::fixed(Offset::from_seconds(*offset).ok()?))
            }
            Self::Named(zone) => Some(zone.clone()),
        }
    }
}

impl From<TimeZone> for Zone {
    /// `UTC` for jiff's UTC, an identifier for a zone with a name and a fixed offset for one without.
    fn from(zone: TimeZone) -> Self {
        if zone == TimeZone::UTC {
            return Self::Utc;
        }
        match zone.iana_name() {
            Some(_) => Self::Named(zone),
            None => Self::Offset(zone.to_offset(Timestamp::UNIX_EPOCH).seconds()),
        }
    }
}

/// An offset the way PHP reads it. Every digit and `:` after the sign belongs to it, and the whole run must be one of
/// `H`, `HH`, `H:M`, `HMM`, `H:MM`, `HH:M`, `HHMM`, `HH:MM`, `HHMMSS` or `HH:MM:SS`.
fn scan_offset(text: &str) -> Option<(i32, usize)> {
    let sign = match text.as_bytes().first()? {
        b'+' => 1,
        b'-' => -1,
        _ => return None,
    };
    let run = text[1..].bytes().take_while(|byte| byte.is_ascii_digit() || *byte == b':').count();
    let body = &text[1..=run];
    let number = |part: &str| (!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())).then(|| part.parse::<i32>().ok()).flatten();
    let (hours, minutes, seconds) = match (body.len(), body.find(':')) {
        (1 | 2, None) => (number(body)?, 0, 0),
        (3, None) => (number(&body[..1])?, number(&body[1..])?, 0),
        (3, Some(1)) => (number(&body[..1])?, number(&body[2..])?, 0),
        (4, None) => (number(&body[..2])?, number(&body[2..])?, 0),
        (4, Some(1)) => (number(&body[..1])?, number(&body[2..])?, 0),
        (4, Some(2)) => (number(&body[..2])?, number(&body[3..])?, 0),
        (5, Some(2)) => (number(&body[..2])?, number(&body[3..])?, 0),
        (6, None) => (number(&body[..2])?, number(&body[2..4])?, number(&body[4..])?),
        (8, Some(2)) if body.as_bytes()[5] == b':' => {
            (number(&body[..2])?, number(&body[3..5])?, number(&body[6..])?)
        }
        _ => return None,
    };
    if minutes > 59 || seconds > 59 {
        return None;
    }
    let offset = sign * (hours * 3600 + minutes * 60 + seconds);
    Offset::from_seconds(offset).ok()?;
    Some((offset, 1 + run))
}

/// A date and time with its time zone: what `DateTime::format()` prints and `createFromFormat()` returns.
///
/// Build one from a jiff `civil::DateTime` (read as UTC), a `Timestamp` (UTC), a `ZonedDateTime`, or with
/// [`PhpDateTime::new`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhpDateTime {
    local: DateTime,
    zone: Zone,
    offset: i32,
    dst: bool,
    abbreviation: String,
}

impl PhpDateTime {
    /// A wall-clock time in `zone`. A time that does not exist there (the hour a daylight saving change skips)
    /// moves forward as PHP moves it, and a time that happens twice is the first one.
    ///
    /// # Errors
    /// When the result falls outside the dates jiff supports (years `-9999` to `9999`).
    pub fn new(local: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
        match &zone {
            Zone::Utc => Ok(Self { local, offset: 0, dst: false, abbreviation: "UTC".into(), zone }),
            Zone::Offset(offset) => {
                let offset = *offset;
                Offset::from_seconds(offset)?;
                let abbreviation = format!("GMT{}", compact_offset(offset));
                Ok(Self { local, offset, dst: false, abbreviation, zone })
            }
            Zone::Abbreviation { name, offset, dst } => {
                Offset::from_seconds(*offset)?;
                let (offset, dst, abbreviation) = (*offset, *dst, name.clone());
                Ok(Self { local, offset, dst, abbreviation, zone })
            }
            Zone::Named(tz) => {
                let zoned = tz.to_ambiguous_zoned_datetime(local).compatible()?;
                Ok(Self::from_zoned(&zoned, zone))
            }
        }
    }

    /// The instant `utc` (a UTC wall-clock time) seen from `zone`.
    ///
    /// # Errors
    /// When the result falls outside the dates jiff supports.
    pub fn from_utc(utc: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
        let instant = TimeZone::UTC.to_timestamp(utc)?;
        Self::from_timestamp(instant, zone)
    }

    /// The instant `timestamp` seen from `zone`.
    ///
    /// # Errors
    /// When the result falls outside the dates jiff supports.
    pub fn from_timestamp(timestamp: Timestamp, zone: Zone) -> Result<Self, jiff::Error> {
        match &zone {
            Zone::Named(tz) => Ok(Self::from_zoned(&timestamp.to_zoned_datetime(tz.clone()), zone)),
            Zone::Utc => Self::new(TimeZone::UTC.to_datetime(timestamp), zone),
            Zone::Offset(offset) | Zone::Abbreviation { offset, .. } => {
                let local = TimeZone::fixed(Offset::from_seconds(*offset)?).to_datetime(timestamp);
                Self::new(local, zone)
            }
        }
    }

    fn from_zoned(date: &ZonedDateTime, zone: Zone) -> Self {
        let info = date.time_zone().to_offset_info(date.timestamp());
        Self {
            local: date.datetime(),
            zone,
            offset: info.offset().seconds(),
            dst: info.dst().is_dst(),
            abbreviation: info.abbreviation().to_owned(),
        }
    }

    /// The same instant in another zone.
    ///
    /// # Errors
    /// When the result falls outside the dates jiff supports.
    pub fn in_zone(&self, zone: Zone) -> Result<Self, jiff::Error> {
        Self::from_timestamp(self.to_timestamp()?, zone)
    }

    /// The wall-clock time, without the zone.
    #[must_use]
    pub const fn datetime(&self) -> &DateTime {
        &self.local
    }

    /// The zone.
    #[must_use]
    pub const fn zone(&self) -> &Zone {
        &self.zone
    }

    /// Seconds east of UTC at this instant (`Z`).
    #[must_use]
    pub const fn offset_seconds(&self) -> i32 {
        self.offset
    }

    /// Whether daylight saving time is in effect (`I`).
    #[must_use]
    pub const fn is_dst(&self) -> bool {
        self.dst
    }

    /// The instant.
    ///
    /// # Errors
    /// When the instant falls outside the range jiff supports.
    pub fn to_timestamp(&self) -> Result<Timestamp, jiff::Error> {
        TimeZone::UTC.to_timestamp(self.local)?.checked_sub(SignedDuration::from_secs(i64::from(self.offset)))
    }

    /// The Unix timestamp (`U`), saturating at the ends of jiff's range.
    #[must_use]
    pub fn timestamp(&self) -> i64 {
        self.to_timestamp().map_or_else(
            |_| if self.local.year() < 0 { Timestamp::MIN.as_second() } else { Timestamp::MAX.as_second() },
            |timestamp| timestamp.as_second(),
        )
    }

    /// The instant as a jiff `ZonedDateTime`.
    ///
    /// # Errors
    /// When the instant falls outside the range jiff supports.
    pub fn to_zoned_datetime(&self) -> Result<ZonedDateTime, jiff::Error> {
        let zone = self.zone.time_zone().ok_or_else(|| jiff::Error::from_args(format_args!("invalid offset")))?;
        Ok(self.to_timestamp()?.to_zoned_datetime(zone))
    }

    /// The abbreviation `T` prints.
    pub(crate) fn abbreviation(&self) -> &str {
        &self.abbreviation
    }
}

/// `+0530`
pub(crate) fn compact_offset(offset: i32) -> String {
    let sign = if offset < 0 { '-' } else { '+' };
    format!("{sign}{:02}{:02}", offset.abs() / 3600, offset.abs() % 3600 / 60)
}

impl From<&Self> for PhpDateTime {
    fn from(date: &Self) -> Self {
        date.clone()
    }
}

impl From<DateTime> for PhpDateTime {
    /// Read as UTC.
    fn from(local: DateTime) -> Self {
        Self { local, zone: Zone::Utc, offset: 0, dst: false, abbreviation: "UTC".into() }
    }
}

impl From<&DateTime> for PhpDateTime {
    /// Read as UTC.
    fn from(local: &DateTime) -> Self {
        (*local).into()
    }
}

impl From<Timestamp> for PhpDateTime {
    fn from(timestamp: Timestamp) -> Self {
        TimeZone::UTC.to_datetime(timestamp).into()
    }
}

impl From<ZonedDateTime> for PhpDateTime {
    fn from(date: ZonedDateTime) -> Self {
        Self::from_zoned(&date, date.time_zone().clone().into())
    }
}