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
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
436
437
438
439
//! `DateTime::createFromFormat()`.

use crate::{
    PhpDatePattern, PhpDateTime, Zone,
    names::{day, month},
    pattern::Token,
};
use jiff::{
    Span, Timestamp,
    civil::{Date, DateTime, Time},
    tz::TimeZone,
};
use std::fmt;

/// Why a value did not match a pattern.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    /// Byte offset in the value where it went wrong.
    pub position: usize,
    /// What went wrong, in the words PHP uses where it has them.
    pub message: String,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} (at position {})", self.message, self.position)
    }
}

impl std::error::Error for ParseError {}

/// The fields a pattern has read so far. `None` is "not in the value".
#[derive(Default)]
struct Fields {
    year: Option<i32>,
    month: Option<u32>,
    day: Option<u32>,
    hour: Option<u32>,
    minute: Option<u32>,
    second: Option<u32>,
    micro: Option<u32>,
    weekday: Option<u32>,
    zone: Option<Zone>,
}

impl Fields {
    /// `!`: the Unix epoch, and no zone.
    fn reset(&mut self) {
        *self = Self {
            year: Some(1970),
            month: Some(1),
            day: Some(1),
            hour: Some(0),
            minute: Some(0),
            second: Some(0),
            micro: Some(0),
            ..Self::default()
        };
    }

    /// `|`: the Unix epoch for every field the value did not set.
    fn reset_unset(&mut self) {
        self.year.get_or_insert(1970);
        self.month.get_or_insert(1);
        self.day.get_or_insert(1);
        self.hour.get_or_insert(0);
        self.minute.get_or_insert(0);
        self.second.get_or_insert(0);
        self.micro.get_or_insert(0);
    }
}

impl PhpDatePattern {
    /// Parse like `DateTime::createFromFormat($pattern, $value, $zone)`, with `now` as the current time: the fields
    /// the value leaves out come from `now`, in the zone the value names or, when it names none, the zone of `now`.
    /// As in PHP, a value that sets an hour, minute or second takes zero for the time fields it leaves out, and `!`
    /// and `|` in the pattern reset fields to the Unix epoch.
    ///
    /// It is stricter than PHP where PHP only warns: a date that does not exist (`31/02/2026`), an hour above 23 or a
    /// text that does not fit is an error, as if you had checked `DateTime::getLastErrors()`. Numbers must start where
    /// the token is (PHP skips junk before them), and the day names `D` and `l` move the date forward to that
    /// weekday, as PHP does. `+` is an error when data follows, because PHP warns about it.
    ///
    /// # Errors
    /// [`ParseError`] when the value does not match the pattern, when the pattern has a token `createFromFormat()` does
    /// not read (`N w W o t L B I Z c r`), or when the result is not a real date and time.
    pub fn parse_at(&self, value: &str, now: &PhpDateTime) -> Result<PhpDateTime, ParseError> {
        self.parse_from(value, now, false)
    }

    /// [`parse_at`](Self::parse_at) with the system clock as the current time, in `zone`.
    ///
    /// # Errors
    /// See [`parse_at`](Self::parse_at).
    pub fn parse_now(&self, value: &str, zone: &Zone) -> Result<PhpDateTime, ParseError> {
        let now = PhpDateTime::from_timestamp(Timestamp::now(), zone.clone())
            .map_err(|error| ParseError { position: 0, message: error.to_string() })?;
        self.parse_at(value, &now)
    }

    /// Parse the way a date filter needs: like `createFromFormat('!' . $pattern, $value)`, plus a check that the value
    /// reads back identically, so `2/2026` is not `m/Y` and `10/02/26 ` is not `d/m/y`. The fields the pattern leaves
    /// out are the Unix epoch's, in UTC. `None` for anything that does not parse.
    #[must_use]
    pub fn parse(&self, value: &str) -> Option<DateTime> {
        let has = |wanted: &[Token]| self.tokens.iter().any(|token| wanted.contains(token));
        if has(&[Token::Hour12, Token::Hour12Padded]) && !has(&[Token::MeridiemLower, Token::MeridiemUpper]) {
            return None;
        }
        let epoch = PhpDateTime::from(DateTime::from_parts(Date::new(1970, 1, 1).ok()?, Time::midnight()));
        let parsed = self.parse_from(value, &epoch, true).ok()?;
        (self.format(&parsed) == value).then(|| *parsed.datetime())
    }

    fn parse_from(&self, value: &str, now: &PhpDateTime, reset: bool) -> Result<PhpDateTime, ParseError> {
        let mut state = Reader { value, position: 0, fields: Fields::default() };
        if reset {
            state.fields.reset();
        }
        state.read(&self.tokens)?;
        state.finish(now)
    }
}

struct Reader<'a> {
    value: &'a str,
    position: usize,
    fields: Fields,
}

const SEPARATORS: &str = ";:/.,-()";

impl Reader<'_> {
    fn error<T>(&self, message: &str) -> Result<T, ParseError> {
        Err(ParseError { position: self.position, message: message.to_owned() })
    }

    fn rest(&self) -> &str {
        &self.value[self.position..]
    }

    /// Digits from the current position: at least `min` and at most `max`.
    fn digits(&mut self, min: usize, max: usize, what: &str) -> Result<(u64, usize), ParseError> {
        let length = self.rest().bytes().take(max).take_while(u8::is_ascii_digit).count();
        if length < min.max(1) {
            return self.error(what);
        }
        let number = self.rest()[..length].parse().map_err(|_| ParseError {
            position: self.position,
            message: what.to_owned(),
        })?;
        self.position += length;
        Ok((number, length))
    }

    fn small(&mut self, min: usize, max: usize, what: &str) -> Result<u32, ParseError> {
        let (number, _) = self.digits(min, max, what)?;
        u32::try_from(number).or_else(|_| self.error(what))
    }

    fn literal(&mut self, expected: char) -> Result<(), ParseError> {
        match self.rest().strip_prefix(expected) {
            Some(_) => {
                self.position += expected.len_utf8();
                Ok(())
            }
            None => self.error("The format separator does not match"),
        }
    }

    fn read(&mut self, tokens: &[Token]) -> Result<(), ParseError> {
        for token in tokens {
            if self.position >= self.value.len() {
                match token {
                    Token::Literal('!') => self.fields.reset(),
                    Token::Literal('|') => self.fields.reset_unset(),
                    Token::Literal(' ' | '*' | '+') => {}
                    _ => return self.error("Not enough data available to satisfy format"),
                }
                continue;
            }
            self.token(*token)?;
        }
        if self.position < self.value.len() {
            return self.error("Trailing data");
        }
        Ok(())
    }

    #[allow(clippy::too_many_lines)]
    fn token(&mut self, token: Token) -> Result<(), ParseError> {
        match token {
            Token::Escaped(c) => self.literal(c)?,
            Token::Literal(' ') => {
                let skipped = self.rest().len() - self.rest().trim_start_matches([' ', '\t', '\u{a0}', '\u{202f}']).len();
                self.position += skipped;
            }
            Token::Literal('#') => match self.rest().chars().next().filter(|c| SEPARATORS.contains(*c)) {
                Some(c) => self.position += c.len_utf8(),
                None => return self.error("The separation symbol ([;:/.,-]) could not be found"),
            },
            Token::Literal('?') => match self.rest().chars().next() {
                Some(c) => self.position += c.len_utf8(),
                None => return self.error("Unexpected end of data"),
            },
            Token::Literal('*') => {
                let length = self
                    .rest()
                    .find(|c: char| c.is_ascii_digit() || c == ' ' || SEPARATORS.contains(c))
                    .unwrap_or(self.rest().len());
                self.position += length;
            }
            Token::Literal('!') => self.fields.reset(),
            Token::Literal('|') => self.fields.reset_unset(),
            Token::Literal('+') => return self.error("Trailing data"),
            Token::Literal(c) => self.literal(c)?,

            Token::Day2 | Token::Day => self.fields.day = Some(self.small(1, 2, "A two digit day could not be found")?),
            Token::DayShort | Token::DayName => match day(self.rest()) {
                Some((weekday, length)) => {
                    self.fields.weekday = Some(weekday);
                    self.position += length;
                }
                None => return self.error("A textual day could not be found"),
            },
            Token::OrdinalSuffix => {
                // PHP skips a suffix when there is one and goes on when there is not.
                let suffix = self.rest().get(..2).map(str::to_ascii_lowercase);
                if matches!(suffix.as_deref(), Some("st" | "nd" | "rd" | "th")) {
                    self.position += 2;
                }
            }
            Token::DayOfYear => {
                if self.fields.year.is_none() {
                    return self.error("A 'day of year' can only come after a year has been found");
                }
                // PHP turns the day of the year into a month and day on the spot; later tokens can still change them.
                let ordinal = self.small(1, 3, "A three digit day-of-year could not be found")?;
                let date = self.fields.year.and_then(|year| roll(year, 1, 1 + ordinal));
                let Some(date) = date else { return self.error("The parsed date was invalid") };
                self.fields.year = Some(i32::from(date.year()));
                self.fields.month = u32::try_from(date.month()).ok();
                self.fields.day = u32::try_from(date.day()).ok();
            }
            Token::MonthName | Token::MonthShort => match month(self.rest()) {
                Some((number, length)) => {
                    self.fields.month = Some(number);
                    self.position += length;
                }
                None => return self.error("A textual month could not be found"),
            },
            Token::Month2 | Token::Month => {
                self.fields.month = Some(self.small(1, 2, "A two digit month could not be found")?);
            }
            Token::Year4 => {
                let (year, _) = self.digits(1, 4, "A four digit year could not be found")?;
                self.fields.year = i32::try_from(year).ok();
            }
            Token::Year2 => {
                let year = self.small(1, 2, "A two digit year could not be found")?;
                self.fields.year = i32::try_from(if year < 70 { 2000 + year } else { 1900 + year }).ok();
            }
            Token::ExpandedYear | Token::ExpandedYearSigned => {
                let sign = match self.rest().chars().next() {
                    Some('+') => Some(1),
                    Some('-') => Some(-1),
                    _ => None,
                };
                self.position += usize::from(sign.is_some());
                let (year, _) = self.digits(1, 19, "A four digit year could not be found")?;
                let year = i32::try_from(year).or_else(|_| self.error("A four digit year could not be found"))?;
                self.fields.year = Some(year * sign.unwrap_or(1));
            }
            Token::MeridiemLower | Token::MeridiemUpper => self.meridian()?,
            Token::Hour12 | Token::Hour12Padded => {
                let hour = self.small(1, 2, "A two digit hour could not be found")?;
                if hour > 12 {
                    return self.error("Hour cannot be higher than 12");
                }
                self.fields.hour = Some(hour);
            }
            Token::Hour24 | Token::Hour24Padded => {
                self.fields.hour = Some(self.small(1, 2, "A two digit hour could not be found")?);
            }
            Token::Minute => self.fields.minute = Some(self.small(2, 2, "A two digit minute could not be found")?),
            Token::Second => self.fields.second = Some(self.small(2, 2, "A two digit second could not be found")?),
            Token::Micro => {
                let (number, length) = self.digits(1, 6, "A six digit microsecond could not be found")?;
                self.fields.micro = u32::try_from(number * 10_u64.pow(u32::try_from(6 - length).unwrap_or(0))).ok();
            }
            Token::Milli => {
                let (number, length) = self.digits(1, 3, "A three digit millisecond could not be found")?;
                self.fields.micro =
                    u32::try_from(number * 10_u64.pow(u32::try_from(3 - length).unwrap_or(0)) * 1000).ok();
            }
            Token::ZoneName | Token::ZoneAbbreviation | Token::OffsetCompact | Token::OffsetColon | Token::OffsetColonZ => {
                match Zone::scan(self.rest()) {
                    Some((zone, length)) => {
                        self.fields.zone = Some(zone);
                        self.position += length;
                    }
                    None => return self.error("The timezone could not be found in the database"),
                }
            }
            Token::Timestamp => self.timestamp()?,
            Token::IsoWeekday
            | Token::Weekday
            | Token::IsoWeek
            | Token::DaysInMonth
            | Token::LeapYear
            | Token::IsoYear
            | Token::Swatch
            | Token::Dst
            | Token::OffsetSeconds
            | Token::Iso8601
            | Token::Rfc2822 => return self.error("The format character is not supported by createFromFormat()"),
        }
        Ok(())
    }

    /// `a` / `A`: `am`, `pm`, `a.m.`, `p.m.`, in any letter case, after an hour.
    fn meridian(&mut self) -> Result<(), ParseError> {
        let Some(hour) = self.fields.hour else {
            return self.error("Meridian can only come after an hour has been found");
        };
        // PHP skips whatever comes before the first `a` or `p`.
        let skipped = self.rest().bytes().take_while(|byte| !matches!(byte, b'a' | b'A' | b'p' | b'P')).count();
        self.position += skipped;
        let rest = self.rest().as_bytes();
        let pm = match rest.first().map(u8::to_ascii_lowercase) {
            Some(b'a') => false,
            Some(b'p') => true,
            _ => return self.error("A meridian could not be found"),
        };
        let mut length = 1;
        // `p.m.` has a dot after each letter; `pm.` is `pm` followed by a pattern character.
        let dotted = rest.get(length) == Some(&b'.');
        if dotted {
            length += 1;
        }
        if rest.get(length).map(u8::to_ascii_lowercase) != Some(b'm') {
            return self.error("A meridian could not be found");
        }
        length += 1;
        if dotted && rest.get(length) == Some(&b'.') {
            length += 1;
        }
        self.position += length;
        self.fields.hour = Some(match (pm, hour) {
            (false, 12) => 0,
            (true, hour) if hour != 12 => hour + 12,
            (_, hour) => hour,
        });
        Ok(())
    }

    /// `U`: seconds since the Unix epoch, in the zone `+00:00`.
    fn timestamp(&mut self) -> Result<(), ParseError> {
        let negative = self.rest().starts_with('-');
        self.position += usize::from(negative);
        let (seconds, _) = self.digits(1, 19, "A unix timestamp could not be found")?;
        let seconds = i64::try_from(seconds).or_else(|_| self.error("A unix timestamp could not be found"))?;
        let Ok(instant) = Timestamp::from_second(if negative { -seconds } else { seconds }) else {
            return self.error("A unix timestamp could not be found");
        };
        let date = TimeZone::UTC.to_datetime(instant);
        let fields = &mut self.fields;
        fields.year = Some(i32::from(date.year()));
        fields.month = u32::try_from(date.month()).ok();
        fields.day = u32::try_from(date.day()).ok();
        fields.hour = u32::try_from(date.hour()).ok();
        fields.minute = u32::try_from(date.minute()).ok();
        fields.second = u32::try_from(date.second()).ok();
        fields.zone = Some(Zone::Offset(0));
        Ok(())
    }

    /// Fill what the value left out from `now` and check that the result exists.
    fn finish(self, now: &PhpDateTime) -> Result<PhpDateTime, ParseError> {
        let Self { value, mut fields, .. } = self;
        let fail = |message: &str| ParseError { position: value.len(), message: message.to_owned() };

        if fields.hour.is_some() || fields.minute.is_some() || fields.second.is_some() || fields.micro.is_some() {
            fields.hour.get_or_insert(0);
            fields.minute.get_or_insert(0);
            fields.second.get_or_insert(0);
            fields.micro.get_or_insert(0);
        }
        let zone = fields.zone.take().unwrap_or_else(|| now.zone().clone());
        // The fields come from `now` as they read on its own clock: a zone in the value only labels the result.
        let today = now.datetime();

        let year = fields.year.unwrap_or_else(|| i32::from(today.year()));
        let month = fields.month.unwrap_or_else(|| u32::try_from(today.month()).unwrap_or(1));
        let day = fields.day.unwrap_or_else(|| u32::try_from(today.day()).unwrap_or(1));
        let complete = fields.year.is_some() && fields.month.is_some() && fields.day.is_some();
        let invalid_date = || fail("The parsed date was invalid");
        let date = if complete {
            let (y, m, d) = (i16::try_from(year), i8::try_from(month), i8::try_from(day));
            Date::new(y.map_err(|_| invalid_date())?, m.map_err(|_| invalid_date())?, d.map_err(|_| invalid_date())?)
                .map_err(|_| invalid_date())?
        } else {
            // PHP only checks a date it read whole; a day or month out of range rolls into the next one.
            roll(year, month, day).ok_or_else(invalid_date)?
        };
        let mut date = date;
        if let Some(weekday) = fields.weekday {
            let current = u32::from(date.weekday().to_monday_zero_offset().unsigned_abs());
            let ahead = (weekday + 7 - current) % 7;
            date = date.checked_add(Span::new().days(i64::from(ahead))).map_err(|_| invalid_date())?;
        }

        let part = |value: Option<u32>, fallback: i32| i32::try_from(value.unwrap_or_else(|| u32::try_from(fallback).unwrap_or(0)));
        let invalid_time = || fail("The parsed time was invalid");
        let hour = part(fields.hour, i32::from(today.hour())).map_err(|_| invalid_time())?;
        let minute = part(fields.minute, i32::from(today.minute())).map_err(|_| invalid_time())?;
        let second = part(fields.second, i32::from(today.second())).map_err(|_| invalid_time())?;
        let micro = fields.micro.map_or_else(|| today.subsec_nanosecond() / 1000, |micro| i32::try_from(micro).unwrap_or(0));
        let time = Time::new(
            i8::try_from(hour).map_err(|_| invalid_time())?,
            i8::try_from(minute).map_err(|_| invalid_time())?,
            i8::try_from(second).map_err(|_| invalid_time())?,
            micro * 1000,
        )
        .map_err(|_| invalid_time())?;
        PhpDateTime::new(DateTime::from_parts(date, time), zone).map_err(|error| fail(&error.to_string()))
    }
}

/// January 1st of `year` plus `month - 1` months plus `day - 1` days, as `mktime()` counts.
fn roll(year: i32, month: u32, day: u32) -> Option<Date> {
    let first = Date::new(i16::try_from(year).ok()?, 1, 1).ok()?;
    // Two sums: a jiff span has one sign, and the months and the days can differ.
    first
        .checked_add(Span::new().try_months(i64::from(month) - 1).ok()?)
        .ok()?
        .checked_add(Span::new().try_days(i64::from(day) - 1).ok()?)
        .ok()
}