php-dates 0.2.1

PHP date() patterns for Rust: strict createFromFormat-style parsing, a pattern resolution contract and a Day.js export, with no framework dependency
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Time zones and the date-time `format()` reads: PHP's three kinds of zone.

use jiff::{
    SignedDuration, Timestamp, ZonedDateTime,
    civil::{self, DateTime},
    tz::{self, AmbiguousOffset, Disambiguation, Offset, TimeZone},
};
use std::{borrow::Cow, fmt};

/// The start of Unix time, as a wall-clock time.
pub(crate) const EPOCH: DateTime = civil::datetime(1970, 1, 1, 0, 0, 0, 0);

/// Zone abbreviations understood by `T`, `e`, `O`, `P` and `p`: name, seconds east of UTC, daylight saving.
///
/// PHP's own table is much longer, and takes the oldest meaning of some names: `KST` is `+08:30` there and `NDT` is
/// `-02:30:52`. Here they are the offsets in use today.
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.
///
/// The variants are open so that they can be matched. When building one by hand, prefer [`Zone::parse`] or the
/// `From<jiff::tz::TimeZone>` conversion: an offset out of range is only reported when a [`PhpDateTime`] is built.
#[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,
    },
    /// A zone with its own rules: an IANA identifier such as `Europe/Madrid`. A jiff zone that has rules but no name
    /// (a POSIX `TZ` string, some system zones) is kept here too, and `e` prints its offset.
    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`, with `GMT` in
    /// capitals). Files of the time zone database that PHP does not take as identifiers (`posixrules`, `localtime`,
    /// `posix/...`, `right/...`, `SystemV/...`) are rejected.
    ///
    /// 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)> {
        // PHP skips `GMT`, in capitals, before a sign; `gmt+2` and `UTC+2` are not zones.
        let prefix = if text.starts_with("GMT+") || text.starts_with("GMT-") { 3 } else { 0 };
        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() || not_an_identifier(word) {
            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()),
        }
    }
}

/// Names jiff resolves from the files of a system's database that PHP does not take as identifiers.
fn not_an_identifier(word: &str) -> bool {
    let lower = word.to_ascii_lowercase();
    matches!(lower.as_str(), "posixrules" | "localtime" | "etc/unknown")
        || ["posix/", "right/", "systemv/"].iter().any(|prefix| lower.starts_with(prefix))
}

impl From<TimeZone> for Zone {
    /// `UTC` for jiff's UTC, [`Zone::Offset`] for an unnamed fixed offset and [`Zone::Named`] for a zone with a name
    /// or with rules of its own.
    fn from(zone: TimeZone) -> Self {
        if zone == TimeZone::UTC {
            return Self::Utc;
        }
        if zone.iana_name().is_some() {
            return Self::Named(zone);
        }
        match zone.to_fixed_offset() {
            Ok(offset) => Self::Offset(offset.seconds()),
            Err(_) => Self::Named(zone),
        }
    }
}

/// 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:`, `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),
        (2, Some(1)) => (number(&body[..1])?, 0, 0),
        (3, Some(2)) => (number(&body[..2])?, 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`].
///
/// It covers every wall-clock time jiff's `civil::DateTime` does (years `-9999` to `9999`), which is a little more than
/// its `Timestamp`: at both ends [`timestamp`](Self::timestamp) still answers, and
/// [`to_timestamp`](Self::to_timestamp) is an error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhpDateTime {
    local: DateTime,
    zone: Zone,
    offset: i32,
    dst: bool,
    abbreviation: Cow<'static, str>,
}

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
    /// ([`Disambiguation::Compatible`]).
    ///
    /// PHP does not always take the first one: for `new DateTime($time, $zone)` and for a `createFromFormat()` value
    /// that names no zone, it takes the second when the clocks go back to UTC+0 or ahead of it, as in `Europe/London`,
    /// `Europe/Madrid` or `Australia/Sydney`. Use [`new_with`](Self::new_with) to choose.
    ///
    /// # Errors
    /// For an offset out of range, or when a skipped hour moves past the last date jiff supports.
    pub fn new(local: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
        Self::new_with(local, zone, Disambiguation::Compatible)
    }

    /// [`new`](Self::new), choosing what happens with a wall-clock time that a [`Zone::Named`] skips or repeats.
    /// The other zones have a single offset, so `disambiguation` changes nothing for them.
    ///
    /// # Errors
    /// Those of [`new`](Self::new), and [`Disambiguation::Reject`] for a skipped or repeated time.
    pub fn new_with(local: DateTime, zone: Zone, disambiguation: Disambiguation) -> Result<Self, jiff::Error> {
        match &zone {
            Zone::Utc => Ok(local.into()),
            Zone::Offset(offset) => {
                let offset = *offset;
                Offset::from_seconds(offset)?;
                let mut abbreviation = String::from("GMT");
                // Writing to a `String` cannot fail.
                let _ = write_offset(&mut abbreviation, offset, "");
                Ok(Self { local, offset, dst: false, abbreviation: abbreviation.into(), zone })
            }
            Zone::Abbreviation { name, offset, dst } => {
                Offset::from_seconds(*offset)?;
                let (offset, dst, abbreviation) = (*offset, *dst, Cow::Owned(name.clone()));
                Ok(Self { local, offset, dst, abbreviation, zone })
            }
            Zone::Named(tz) => {
                let (local, offset) = resolve(tz, local, disambiguation)?;
                let offset = offset.seconds();
                // Past the ends of `Timestamp` there are no more transitions: the rules at the end still hold.
                let info = tz.to_offset_info(clamped_instant(local, offset));
                let (dst, abbreviation) = (info.dst().is_dst(), Cow::Owned(info.abbreviation().to_owned()));
                Ok(Self { local, offset, dst, abbreviation, zone })
            }
        }
    }

    /// The instant `utc` (a UTC wall-clock time) seen from `zone`.
    ///
    /// # Errors
    /// For an offset out of range, or a result outside the dates jiff supports.
    pub fn from_utc(utc: DateTime, zone: Zone) -> Result<Self, jiff::Error> {
        if let Ok(instant) = TimeZone::UTC.to_timestamp(utc) {
            return Self::from_timestamp(instant, zone);
        }
        let offset = match &zone {
            Zone::Utc => 0,
            Zone::Offset(offset) | Zone::Abbreviation { offset, .. } => Offset::from_seconds(*offset)?.seconds(),
            Zone::Named(tz) => tz.to_offset(clamped_instant(utc, 0)).seconds(),
        };
        Self::new(utc.checked_add(SignedDuration::from_secs(i64::from(offset)))?, zone)
    }

    /// The instant `timestamp` seen from `zone`.
    ///
    /// # Errors
    /// For an offset out of range.
    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: Cow::Owned(info.abbreviation().to_owned()),
        }
    }

    /// The same instant in another zone.
    ///
    /// # Errors
    /// For an offset out of range, or a result outside the dates jiff supports.
    pub fn in_zone(&self, zone: Zone) -> Result<Self, jiff::Error> {
        Self::from_utc(self.local.checked_sub(SignedDuration::from_secs(i64::from(self.offset)))?, 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 zone abbreviation at this instant, as `T` prints it.
    #[must_use]
    pub fn abbreviation(&self) -> &str {
        &self.abbreviation
    }

    /// The instant.
    ///
    /// # Errors
    /// When the instant falls outside the range of jiff's `Timestamp`.
    pub fn to_timestamp(&self) -> Result<Timestamp, jiff::Error> {
        Timestamp::from_duration(since_epoch(self.local, self.offset))
    }

    /// The Unix timestamp (`U`): whole seconds, rounded down as PHP does, so half a second before 1970 is `-1`.
    #[must_use]
    pub fn timestamp(&self) -> i64 {
        let since = since_epoch(self.local, self.offset);
        since.as_secs() - i64::from(since.subsec_nanos() < 0)
    }

    /// The instant as a jiff `ZonedDateTime`.
    ///
    /// # Errors
    /// When the instant falls outside the range of jiff's `Timestamp`.
    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 time from the epoch to the wall-clock time `local` seen at `offset`, over the whole range of `civil::DateTime`.
fn since_epoch(local: DateTime, offset: i32) -> SignedDuration {
    local.duration_since(EPOCH) - SignedDuration::from_secs(i64::from(offset))
}

/// The instant of `local` at `offset`, or the nearest one jiff has.
fn clamped_instant(local: DateTime, offset: i32) -> Timestamp {
    Timestamp::from_duration(since_epoch(local, offset)).unwrap_or(if local.year() < 0 {
        Timestamp::MIN
    } else {
        Timestamp::MAX
    })
}

/// The wall-clock time and offset of `local` in `zone`. Unlike jiff's own disambiguation it does not need the instant,
/// so it also answers at the ends of the calendar.
fn resolve(
    zone: &TimeZone,
    local: DateTime,
    disambiguation: Disambiguation,
) -> Result<(DateTime, Offset), jiff::Error> {
    let rejected = |what| jiff::Error::from_args(format_args!("the local time {local} is {what} in this time zone"));
    let gap = |before: Offset, after: Offset| SignedDuration::from_secs(i64::from(after.seconds() - before.seconds()));
    Ok(match zone.to_ambiguous_timestamp(local).offset() {
        AmbiguousOffset::Unambiguous { offset } => (local, offset),
        AmbiguousOffset::Gap { before, after } => match disambiguation {
            Disambiguation::Compatible | Disambiguation::Later => (local.checked_add(gap(before, after))?, after),
            Disambiguation::Earlier => (local.checked_sub(gap(before, after))?, before),
            _ => return Err(rejected("skipped")),
        },
        AmbiguousOffset::Fold { before, after } => match disambiguation {
            Disambiguation::Compatible | Disambiguation::Earlier => (local, before),
            Disambiguation::Later => (local, after),
            _ => return Err(rejected("repeated")),
        },
    })
}

/// `+0530` with an empty `separator`, `+05:30` with `:`.
pub(crate) fn write_offset<W: fmt::Write + ?Sized>(out: &mut W, offset: i32, separator: &str) -> fmt::Result {
    let sign = if offset < 0 { '-' } else { '+' };
    let seconds = offset.unsigned_abs();
    write!(out, "{sign}{:02}{separator}{:02}", seconds / 3600, seconds % 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: Cow::Borrowed("UTC") }
    }
}

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 {
    /// The wall-clock time, offset and zone of `date`.
    fn from(date: ZonedDateTime) -> Self {
        Self::from_zoned(&date, date.time_zone().clone().into())
    }
}