Skip to main content

php_dates/
parse.rs

1//! `DateTime::createFromFormat()`.
2
3use crate::{
4    PhpDatePattern, PhpDateTime, Zone,
5    names::{day, month},
6    pattern::Token,
7    zone::EPOCH,
8};
9use jiff::{
10    SignedDuration, Span, Timestamp,
11    civil::{Date, DateTime, Time},
12    tz::Disambiguation,
13};
14use std::fmt;
15
16/// Why a value did not match a pattern.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ParseError {
19    /// Byte offset in the value where it went wrong.
20    pub position: usize,
21    /// What went wrong, in the words PHP uses where it has them.
22    pub message: String,
23}
24
25impl fmt::Display for ParseError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        write!(f, "{} (at position {})", self.message, self.position)
28    }
29}
30
31impl std::error::Error for ParseError {}
32
33/// The fields a pattern has read so far. `None` is "not in the value".
34#[derive(Default)]
35struct Fields {
36    year: Option<i32>,
37    month: Option<u32>,
38    day: Option<u32>,
39    hour: Option<u32>,
40    minute: Option<u32>,
41    second: Option<u32>,
42    micro: Option<u32>,
43    weekday: Option<u32>,
44    zone: Option<Zone>,
45    /// The value named `zone` by identifier (`Europe/Madrid`, `UTC`), not by offset or abbreviation.
46    identifier: bool,
47}
48
49impl Fields {
50    /// `!`: the Unix epoch. As in PHP, a day name read before stays, and so does an offset or an abbreviation;
51    /// an identifier is dropped.
52    fn reset(&mut self) {
53        let zone = self.zone.take().filter(|_| !self.identifier);
54        *self = Self {
55            year: Some(1970),
56            month: Some(1),
57            day: Some(1),
58            hour: Some(0),
59            minute: Some(0),
60            second: Some(0),
61            micro: Some(0),
62            weekday: self.weekday,
63            zone,
64            identifier: false,
65        };
66    }
67
68    /// `|`: the Unix epoch for every field the value did not set.
69    fn reset_unset(&mut self) {
70        self.year.get_or_insert(1970);
71        self.month.get_or_insert(1);
72        self.day.get_or_insert(1);
73        self.hour.get_or_insert(0);
74        self.minute.get_or_insert(0);
75        self.second.get_or_insert(0);
76        self.micro.get_or_insert(0);
77    }
78}
79
80impl PhpDatePattern {
81    /// Parse like `DateTime::createFromFormat($pattern, $value, $zone)`, with `now` as the current time: the fields
82    /// the value leaves out come from `now`, in the zone the value names or, when it names none, the zone of `now`.
83    /// As in PHP, a value that sets an hour, minute or second takes zero for the time fields it leaves out, a value
84    /// that sets any date or time field takes zero microseconds, and `!` and `|` in the pattern reset fields to the
85    /// Unix epoch.
86    ///
87    /// It is stricter than PHP where PHP only warns: a date that does not exist (`31/02/2026`), an hour above 23 or a
88    /// text that does not fit is an error, as if you had checked `DateTime::getLastErrors()`. Numbers must start where
89    /// the token is, and the day names `D` and `l` move the date forward to that weekday, as PHP does. Data after the
90    /// last token is an error even with `+`, because PHP warns about it.
91    ///
92    /// A wall-clock time that a named zone repeats is the first one. When the value names no zone, PHP takes the second
93    /// if the clocks go back to UTC+0 or ahead of it (`Europe/London`, `Europe/Madrid`); see
94    /// [`parse_at_with`](Self::parse_at_with).
95    ///
96    /// ```
97    /// use php_dates::{PhpDatePattern, PhpDateTime};
98    ///
99    /// let now = PhpDateTime::from(jiff::civil::date(2026, 3, 15).at(10, 20, 30, 0));
100    /// let parsed = PhpDatePattern::compile("d/m H:i")?.parse_at("10/02 13:05", &now)?;
101    /// assert_eq!(parsed.datetime().to_string(), "2026-02-10T13:05:00");
102    /// # Ok::<(), Box<dyn std::error::Error>>(())
103    /// ```
104    ///
105    /// # Errors
106    /// [`ParseError`] when the value does not match the pattern, when the pattern has a token `createFromFormat()` does
107    /// not read (`N w W o t L B I Z c r`), or when the result is not a real date and time.
108    pub fn parse_at(&self, value: &str, now: &PhpDateTime) -> Result<PhpDateTime, ParseError> {
109        self.parse_at_with(value, now, Disambiguation::Compatible)
110    }
111
112    /// [`parse_at`](Self::parse_at), choosing what happens with a wall-clock time that a named zone skips or repeats.
113    ///
114    /// # Errors
115    /// Those of [`parse_at`](Self::parse_at), and [`Disambiguation::Reject`] for a skipped or repeated time.
116    pub fn parse_at_with(
117        &self,
118        value: &str,
119        now: &PhpDateTime,
120        disambiguation: Disambiguation,
121    ) -> Result<PhpDateTime, ParseError> {
122        self.parse_from(value, now, false, disambiguation)
123    }
124
125    /// [`parse_at`](Self::parse_at) with the system clock as the current time, in `zone`.
126    ///
127    /// # Errors
128    /// See [`parse_at`](Self::parse_at).
129    pub fn parse_now(&self, value: &str, zone: &Zone) -> Result<PhpDateTime, ParseError> {
130        let now = PhpDateTime::from_timestamp(Timestamp::now(), zone.clone())
131            .map_err(|error| ParseError { position: 0, message: error.to_string() })?;
132        self.parse_at(value, &now)
133    }
134
135    /// Parse the way a date filter needs: like `createFromFormat('!' . $pattern, $value)`, plus a check that the value
136    /// reads back identically, so `2/2026` is not `m/Y` and `10/02/26 ` is not `d/m/y`. The fields the pattern leaves
137    /// out are the Unix epoch's, in UTC. `None` for anything that does not parse.
138    ///
139    /// Three things to know:
140    ///
141    /// - A 12-hour pattern (`h` or `g`) without `a` or `A` is always `None`: `01:30` does not say which half of the day.
142    /// - The result is the wall-clock time. A zone read by the pattern (`e T O P p`) is checked and then dropped; use
143    ///   [`parse_at`](Self::parse_at) to keep it.
144    /// - As in PHP, `y` reads `00`-`69` as 2000-2069 and `70`-`99` as 1970-1999, so a year outside 1970-2069 formatted
145    ///   with `y` reads back as a different one.
146    ///
147    /// ```
148    /// use php_dates::PhpDatePattern;
149    ///
150    /// let pattern = PhpDatePattern::compile("d/m/Y")?;
151    /// assert_eq!(pattern.parse("10/02/2026"), Some(jiff::civil::date(2026, 2, 10).at(0, 0, 0, 0)));
152    /// assert_eq!(pattern.parse("10/2/2026"), None);
153    /// # Ok::<(), php_dates::Error>(())
154    /// ```
155    #[must_use]
156    pub fn parse(&self, value: &str) -> Option<DateTime> {
157        let has = |wanted: &[Token]| self.tokens.iter().any(|token| wanted.contains(token));
158        if has(&[Token::Hour12, Token::Hour12Padded]) && !has(&[Token::MeridiemLower, Token::MeridiemUpper]) {
159            return None;
160        }
161        let epoch = PhpDateTime::from(EPOCH);
162        let parsed = self.parse_from(value, &epoch, true, Disambiguation::Compatible).ok()?;
163        let mut left = Matching(value);
164        self.format_into(&mut left, &parsed).ok()?;
165        left.0.is_empty().then(|| *parsed.datetime())
166    }
167
168    fn parse_from(
169        &self,
170        value: &str,
171        now: &PhpDateTime,
172        reset: bool,
173        disambiguation: Disambiguation,
174    ) -> Result<PhpDateTime, ParseError> {
175        let mut state = Reader { value, position: 0, fields: Fields::default() };
176        if reset {
177            state.fields.reset();
178        }
179        state.read(&self.tokens)?;
180        state.finish(now, disambiguation)
181    }
182}
183
184/// Compares what is written with the text left to match, so reading back needs no second `String`.
185struct Matching<'a>(&'a str);
186
187impl fmt::Write for Matching<'_> {
188    fn write_str(&mut self, written: &str) -> fmt::Result {
189        self.0 = self.0.strip_prefix(written).ok_or(fmt::Error)?;
190        Ok(())
191    }
192}
193
194struct Reader<'a> {
195    value: &'a str,
196    position: usize,
197    fields: Fields,
198}
199
200const SEPARATORS: &str = ";:/.,-()";
201
202impl Reader<'_> {
203    fn error<T>(&self, message: &str) -> Result<T, ParseError> {
204        Err(ParseError { position: self.position, message: message.to_owned() })
205    }
206
207    fn rest(&self) -> &str {
208        &self.value[self.position..]
209    }
210
211    /// Digits from the current position: at least `min` and at most `max`.
212    fn digits(&mut self, min: usize, max: usize, what: &str) -> Result<(u64, usize), ParseError> {
213        let length = self.rest().bytes().take(max).take_while(u8::is_ascii_digit).count();
214        if length < min.max(1) {
215            return self.error(what);
216        }
217        let number = self.rest()[..length]
218            .parse()
219            .map_err(|_| ParseError { position: self.position, message: what.to_owned() })?;
220        self.position += length;
221        Ok((number, length))
222    }
223
224    fn small(&mut self, min: usize, max: usize, what: &str) -> Result<u32, ParseError> {
225        let (number, _) = self.digits(min, max, what)?;
226        u32::try_from(number).or_else(|_| self.error(what))
227    }
228
229    fn literal(&mut self, expected: char) -> Result<(), ParseError> {
230        match self.rest().strip_prefix(expected) {
231            Some(_) => {
232                self.position += expected.len_utf8();
233                Ok(())
234            }
235            None => self.error("The format separator does not match"),
236        }
237    }
238
239    fn read(&mut self, tokens: &[Token]) -> Result<(), ParseError> {
240        for token in tokens {
241            if self.position >= self.value.len() {
242                match token {
243                    Token::Literal('!') => self.fields.reset(),
244                    Token::Literal('|') => self.fields.reset_unset(),
245                    Token::Literal('+') => {}
246                    _ => return self.error("Not enough data available to satisfy format"),
247                }
248                continue;
249            }
250            self.token(*token)?;
251        }
252        if self.position < self.value.len() {
253            return self.error("Trailing data");
254        }
255        Ok(())
256    }
257
258    #[allow(clippy::too_many_lines)]
259    fn token(&mut self, token: Token) -> Result<(), ParseError> {
260        match token {
261            Token::Escaped(c) => self.literal(c)?,
262            Token::Literal(' ') => {
263                let skipped =
264                    self.rest().len() - self.rest().trim_start_matches([' ', '\t', '\u{a0}', '\u{202f}']).len();
265                self.position += skipped;
266            }
267            Token::Literal('#') => match self.rest().chars().next().filter(|c| SEPARATORS.contains(*c)) {
268                Some(c) => self.position += c.len_utf8(),
269                None => return self.error("The separation symbol ([;:/.,-]) could not be found"),
270            },
271            Token::Literal('?') => match self.rest().chars().next() {
272                Some(c) => self.position += c.len_utf8(),
273                None => return self.error("Unexpected end of data"),
274            },
275            Token::Literal('*') => {
276                // At least one character, then up to a digit or one of ` \t.,:;/-`: parentheses do not stop it.
277                let mut rest = self.rest().chars();
278                let first = rest.next().map_or(0, char::len_utf8);
279                let rest = rest.as_str();
280                let more = rest.find(|c: char| c.is_ascii_digit() || " \t.,:;/-".contains(c)).unwrap_or(rest.len());
281                self.position += first + more;
282            }
283            Token::Literal('!') => self.fields.reset(),
284            Token::Literal('|') => self.fields.reset_unset(),
285            // `+` allows trailing data with a warning, which is an error here anyway.
286            Token::Literal('+') => {}
287            Token::Literal(c) => self.literal(c)?,
288
289            Token::Day2 | Token::Day => {
290                self.fields.day = Some(self.small(1, 2, "A two digit day could not be found")?)
291            }
292            Token::DayShort | Token::DayName => match day(self.rest()) {
293                Some((weekday, length)) => {
294                    self.fields.weekday = Some(weekday);
295                    self.position += length;
296                }
297                None => return self.error("A textual day could not be found"),
298            },
299            Token::OrdinalSuffix => {
300                // PHP skips a suffix when there is one and goes on when there is not.
301                let suffix = self.rest().get(..2).map(str::to_ascii_lowercase);
302                if matches!(suffix.as_deref(), Some("st" | "nd" | "rd" | "th")) {
303                    self.position += 2;
304                }
305            }
306            Token::DayOfYear => {
307                if self.fields.year.is_none() {
308                    return self.error("A 'day of year' can only come after a year has been found");
309                }
310                // PHP turns the day of the year into a month and day on the spot; later tokens can still change them.
311                let ordinal = self.small(1, 3, "A three digit day-of-year could not be found")?;
312                let date = self.fields.year.and_then(|year| roll(year, 1, 1 + ordinal));
313                let Some(date) = date else { return self.error("The parsed date was invalid") };
314                self.fields.year = Some(i32::from(date.year()));
315                self.fields.month = u32::try_from(date.month()).ok();
316                self.fields.day = u32::try_from(date.day()).ok();
317            }
318            Token::MonthName | Token::MonthShort => match month(self.rest()) {
319                Some((number, length)) => {
320                    self.fields.month = Some(number);
321                    self.position += length;
322                }
323                None => return self.error("A textual month could not be found"),
324            },
325            Token::Month2 | Token::Month => {
326                self.fields.month = Some(self.small(1, 2, "A two digit month could not be found")?);
327            }
328            Token::Year4 => {
329                let (year, _) = self.digits(1, 4, "A four digit year could not be found")?;
330                self.fields.year = i32::try_from(year).ok();
331            }
332            Token::Year2 => {
333                let year = self.small(1, 2, "A two digit year could not be found")?;
334                self.fields.year = i32::try_from(if year < 70 { 2000 + year } else { 1900 + year }).ok();
335            }
336            Token::ExpandedYear | Token::ExpandedYearSigned => {
337                let sign = match self.rest().chars().next() {
338                    Some('+') => Some(1),
339                    Some('-') => Some(-1),
340                    _ => None,
341                };
342                self.position += usize::from(sign.is_some());
343                let (year, _) = self.digits(1, 19, "A four digit year could not be found")?;
344                let year = i32::try_from(year).or_else(|_| self.error("A four digit year could not be found"))?;
345                self.fields.year = Some(year * sign.unwrap_or(1));
346            }
347            Token::MeridiemLower | Token::MeridiemUpper => self.meridian()?,
348            Token::Hour12 | Token::Hour12Padded => {
349                let hour = self.small(1, 2, "A two digit hour could not be found")?;
350                if hour > 12 {
351                    return self.error("Hour cannot be higher than 12");
352                }
353                self.fields.hour = Some(hour);
354            }
355            Token::Hour24 | Token::Hour24Padded => {
356                self.fields.hour = Some(self.small(1, 2, "A two digit hour could not be found")?);
357            }
358            Token::Minute => self.fields.minute = Some(self.small(2, 2, "A two digit minute could not be found")?),
359            Token::Second => self.fields.second = Some(self.small(2, 2, "A two digit second could not be found")?),
360            Token::Micro => {
361                let (number, length) = self.digits(1, 6, "A six digit microsecond could not be found")?;
362                self.fields.micro = u32::try_from(number * 10_u64.pow(u32::try_from(6 - length).unwrap_or(0))).ok();
363            }
364            Token::Milli => {
365                let (number, length) = self.digits(1, 3, "A three digit millisecond could not be found")?;
366                self.fields.micro =
367                    u32::try_from(number * 10_u64.pow(u32::try_from(3 - length).unwrap_or(0)) * 1000).ok();
368            }
369            Token::ZoneName
370            | Token::ZoneAbbreviation
371            | Token::OffsetCompact
372            | Token::OffsetColon
373            | Token::OffsetColonZ => self.zone()?,
374            Token::Timestamp => self.timestamp()?,
375            Token::IsoWeekday
376            | Token::Weekday
377            | Token::IsoWeek
378            | Token::DaysInMonth
379            | Token::LeapYear
380            | Token::IsoYear
381            | Token::Swatch
382            | Token::Dst
383            | Token::OffsetSeconds
384            | Token::Iso8601
385            | Token::Rfc2822 => return self.error("The format character is not supported by createFromFormat()"),
386        }
387        Ok(())
388    }
389
390    /// `a` / `A`: `am`, `pm`, `a.m.`, `p.m.`, in any letter case, after an hour.
391    fn meridian(&mut self) -> Result<(), ParseError> {
392        let Some(hour) = self.fields.hour else {
393            return self.error("Meridian can only come after an hour has been found");
394        };
395        // PHP skips whatever comes before the first `a` or `p`.
396        let skipped = self.rest().bytes().take_while(|byte| !matches!(byte, b'a' | b'A' | b'p' | b'P')).count();
397        self.position += skipped;
398        let rest = self.rest().as_bytes();
399        let pm = match rest.first().map(u8::to_ascii_lowercase) {
400            Some(b'a') => false,
401            Some(b'p') => true,
402            _ => return self.error("A meridian could not be found"),
403        };
404        let m = |index: usize| matches!(rest.get(index), Some(b'm' | b'M'));
405        // `pm` or `p.m.`, with both dots; `pm.` is `pm` followed by a pattern character.
406        let length = match rest.get(1) {
407            Some(b'.') if m(2) && rest.get(3) == Some(&b'.') => 4,
408            _ if m(1) => 2,
409            _ => return self.error("A meridian could not be found"),
410        };
411        self.position += length;
412        self.fields.hour = Some(match (pm, hour) {
413            (false, 12) => 0,
414            (true, hour) if hour != 12 => hour + 12,
415            (_, hour) => hour,
416        });
417        Ok(())
418    }
419
420    /// A zone, which PHP lets be preceded by spaces and parentheses: `(CET)`.
421    fn zone(&mut self) -> Result<(), ParseError> {
422        let rest = self.rest();
423        let text = rest.trim_start_matches([' ', '\t', '(']);
424        let skipped = rest.len() - text.len();
425        let mut open = rest[..skipped].matches('(').count();
426        let Some((zone, length)) = Zone::scan(text) else {
427            return self.error("The timezone could not be found in the database");
428        };
429        self.fields.identifier = matches!(zone, Zone::Named(_)) || &text[..length] == "UTC";
430        self.fields.zone = Some(zone);
431        self.position += skipped + length;
432        while open > 0 && self.rest().starts_with(')') {
433            self.position += 1;
434            open -= 1;
435        }
436        Ok(())
437    }
438
439    /// `U`: seconds since the Unix epoch, in the zone `+00:00`.
440    fn timestamp(&mut self) -> Result<(), ParseError> {
441        let negative = self.rest().starts_with('-');
442        self.position += usize::from(negative || self.rest().starts_with('+'));
443        let (seconds, _) = self.digits(1, 19, "A unix timestamp could not be found")?;
444        let seconds = i64::try_from(seconds).or_else(|_| self.error("A unix timestamp could not be found"))?;
445        // Civil arithmetic: it reaches the end of the year 9999, further than jiff's `Timestamp`.
446        let since = SignedDuration::from_secs(if negative { -seconds } else { seconds });
447        let Ok(date) = EPOCH.checked_add(since) else {
448            return self.error("A unix timestamp could not be found");
449        };
450        let fields = &mut self.fields;
451        fields.year = Some(i32::from(date.year()));
452        fields.month = u32::try_from(date.month()).ok();
453        fields.day = u32::try_from(date.day()).ok();
454        fields.hour = u32::try_from(date.hour()).ok();
455        fields.minute = u32::try_from(date.minute()).ok();
456        fields.second = u32::try_from(date.second()).ok();
457        fields.zone = Some(Zone::Offset(0));
458        fields.identifier = false;
459        Ok(())
460    }
461
462    /// Fill what the value left out from `now` and check that the result exists.
463    fn finish(self, now: &PhpDateTime, disambiguation: Disambiguation) -> Result<PhpDateTime, ParseError> {
464        let Self { value, mut fields, .. } = self;
465        let fail = |message: &str| ParseError { position: value.len(), message: message.to_owned() };
466
467        if fields.hour.is_some() || fields.minute.is_some() || fields.second.is_some() || fields.micro.is_some() {
468            fields.hour.get_or_insert(0);
469            fields.minute.get_or_insert(0);
470            fields.second.get_or_insert(0);
471            fields.micro.get_or_insert(0);
472        }
473        // A value that sets any date or time field has no microseconds unless it says so; one that only names a day
474        // or a zone keeps those of `now`.
475        // The hour is filled above when only a minute or a second was read.
476        if fields.year.is_some() || fields.month.is_some() || fields.day.is_some() || fields.hour.is_some() {
477            fields.micro.get_or_insert(0);
478        }
479        let zone = fields.zone.take().unwrap_or_else(|| now.zone().clone());
480        // The fields come from `now` as they read on its own clock: a zone in the value only labels the result.
481        let today = now.datetime();
482
483        let year = fields.year.unwrap_or_else(|| i32::from(today.year()));
484        let month = fields.month.unwrap_or_else(|| u32::try_from(today.month()).unwrap_or(1));
485        let day = fields.day.unwrap_or_else(|| u32::try_from(today.day()).unwrap_or(1));
486        let complete = fields.year.is_some() && fields.month.is_some() && fields.day.is_some();
487        let invalid_date = || fail("The parsed date was invalid");
488        let date = if complete {
489            let (y, m, d) = (i16::try_from(year), i8::try_from(month), i8::try_from(day));
490            Date::new(y.map_err(|_| invalid_date())?, m.map_err(|_| invalid_date())?, d.map_err(|_| invalid_date())?)
491                .map_err(|_| invalid_date())?
492        } else {
493            // PHP only checks a date it read whole; a day or month out of range rolls into the next one.
494            roll(year, month, day).ok_or_else(invalid_date)?
495        };
496        let mut date = date;
497        if let Some(weekday) = fields.weekday {
498            let current = u32::from(date.weekday().to_monday_zero_offset().unsigned_abs());
499            let ahead = (weekday + 7 - current) % 7;
500            date = date.checked_add(Span::new().days(i64::from(ahead))).map_err(|_| invalid_date())?;
501        }
502
503        let part = |value: Option<u32>, fallback: i32| {
504            i32::try_from(value.unwrap_or_else(|| u32::try_from(fallback).unwrap_or(0)))
505        };
506        let invalid_time = || fail("The parsed time was invalid");
507        let hour = part(fields.hour, i32::from(today.hour())).map_err(|_| invalid_time())?;
508        let minute = part(fields.minute, i32::from(today.minute())).map_err(|_| invalid_time())?;
509        let second = part(fields.second, i32::from(today.second())).map_err(|_| invalid_time())?;
510        let micro =
511            fields.micro.map_or_else(|| today.subsec_nanosecond() / 1000, |micro| i32::try_from(micro).unwrap_or(0));
512        let time = Time::new(
513            i8::try_from(hour).map_err(|_| invalid_time())?,
514            i8::try_from(minute).map_err(|_| invalid_time())?,
515            i8::try_from(second).map_err(|_| invalid_time())?,
516            micro * 1000,
517        )
518        .map_err(|_| invalid_time())?;
519        PhpDateTime::new_with(DateTime::from_parts(date, time), zone, disambiguation)
520            .map_err(|error| fail(&error.to_string()))
521    }
522}
523
524/// January 1st of `year` plus `month - 1` months plus `day - 1` days, as `mktime()` counts.
525fn roll(year: i32, month: u32, day: u32) -> Option<Date> {
526    let first = Date::new(i16::try_from(year).ok()?, 1, 1).ok()?;
527    // Two sums: a jiff span has one sign, and the months and the days can differ.
528    first
529        .checked_add(Span::new().try_months(i64::from(month) - 1).ok()?)
530        .ok()?
531        .checked_add(Span::new().try_days(i64::from(day) - 1).ok()?)
532        .ok()
533}