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