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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! `DateTime::createFromFormat()`.

use crate::{
    PhpDatePattern, PhpDateTime, Zone,
    names::{day, month},
    pattern::Token,
    zone::EPOCH,
};
use jiff::{
    SignedDuration, Span, Timestamp,
    civil::{Date, DateTime, Time},
    tz::Disambiguation,
};
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>,
    /// The value named `zone` by identifier (`Europe/Madrid`, `UTC`), not by offset or abbreviation.
    identifier: bool,
}

impl Fields {
    /// `!`: the Unix epoch. As in PHP, a day name read before stays, and so does an offset or an abbreviation;
    /// an identifier is dropped.
    fn reset(&mut self) {
        let zone = self.zone.take().filter(|_| !self.identifier);
        *self = Self {
            year: Some(1970),
            month: Some(1),
            day: Some(1),
            hour: Some(0),
            minute: Some(0),
            second: Some(0),
            micro: Some(0),
            weekday: self.weekday,
            zone,
            identifier: false,
        };
    }

    /// `|`: 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, a value
    /// that sets any date or time field takes zero microseconds, 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, and the day names `D` and `l` move the date forward to that weekday, as PHP does. Data after the
    /// last token is an error even with `+`, because PHP warns about it.
    ///
    /// A wall-clock time that a named zone repeats is the first one. When the value names no zone, PHP takes the second
    /// if the clocks go back to UTC+0 or ahead of it (`Europe/London`, `Europe/Madrid`); see
    /// [`parse_at_with`](Self::parse_at_with).
    ///
    /// ```
    /// use php_dates::{PhpDatePattern, PhpDateTime};
    ///
    /// let now = PhpDateTime::from(jiff::civil::date(2026, 3, 15).at(10, 20, 30, 0));
    /// let parsed = PhpDatePattern::compile("d/m H:i")?.parse_at("10/02 13:05", &now)?;
    /// assert_eq!(parsed.datetime().to_string(), "2026-02-10T13:05:00");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # 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_at_with(value, now, Disambiguation::Compatible)
    }

    /// [`parse_at`](Self::parse_at), choosing what happens with a wall-clock time that a named zone skips or repeats.
    ///
    /// # Errors
    /// Those of [`parse_at`](Self::parse_at), and [`Disambiguation::Reject`] for a skipped or repeated time.
    pub fn parse_at_with(
        &self,
        value: &str,
        now: &PhpDateTime,
        disambiguation: Disambiguation,
    ) -> Result<PhpDateTime, ParseError> {
        self.parse_from(value, now, false, disambiguation)
    }

    /// [`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.
    ///
    /// Three things to know:
    ///
    /// - A 12-hour pattern (`h` or `g`) without `a` or `A` is always `None`: `01:30` does not say which half of the day.
    /// - The result is the wall-clock time. A zone read by the pattern (`e T O P p`) is checked and then dropped; use
    ///   [`parse_at`](Self::parse_at) to keep it.
    /// - As in PHP, `y` reads `00`-`69` as 2000-2069 and `70`-`99` as 1970-1999, so a year outside 1970-2069 formatted
    ///   with `y` reads back as a different one.
    ///
    /// ```
    /// use php_dates::PhpDatePattern;
    ///
    /// let pattern = PhpDatePattern::compile("d/m/Y")?;
    /// assert_eq!(pattern.parse("10/02/2026"), Some(jiff::civil::date(2026, 2, 10).at(0, 0, 0, 0)));
    /// assert_eq!(pattern.parse("10/2/2026"), None);
    /// # Ok::<(), php_dates::Error>(())
    /// ```
    #[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(EPOCH);
        let parsed = self.parse_from(value, &epoch, true, Disambiguation::Compatible).ok()?;
        let mut left = Matching(value);
        self.format_into(&mut left, &parsed).ok()?;
        left.0.is_empty().then(|| *parsed.datetime())
    }

    fn parse_from(
        &self,
        value: &str,
        now: &PhpDateTime,
        reset: bool,
        disambiguation: Disambiguation,
    ) -> 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, disambiguation)
    }
}

/// Compares what is written with the text left to match, so reading back needs no second `String`.
struct Matching<'a>(&'a str);

impl fmt::Write for Matching<'_> {
    fn write_str(&mut self, written: &str) -> fmt::Result {
        self.0 = self.0.strip_prefix(written).ok_or(fmt::Error)?;
        Ok(())
    }
}

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('*') => {
                // At least one character, then up to a digit or one of ` \t.,:;/-`: parentheses do not stop it.
                let mut rest = self.rest().chars();
                let first = rest.next().map_or(0, char::len_utf8);
                let rest = rest.as_str();
                let more = rest.find(|c: char| c.is_ascii_digit() || " \t.,:;/-".contains(c)).unwrap_or(rest.len());
                self.position += first + more;
            }
            Token::Literal('!') => self.fields.reset(),
            Token::Literal('|') => self.fields.reset_unset(),
            // `+` allows trailing data with a warning, which is an error here anyway.
            Token::Literal('+') => {}
            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 => self.zone()?,
            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 m = |index: usize| matches!(rest.get(index), Some(b'm' | b'M'));
        // `pm` or `p.m.`, with both dots; `pm.` is `pm` followed by a pattern character.
        let length = match rest.get(1) {
            Some(b'.') if m(2) && rest.get(3) == Some(&b'.') => 4,
            _ if m(1) => 2,
            _ => return self.error("A meridian could not be found"),
        };
        self.position += length;
        self.fields.hour = Some(match (pm, hour) {
            (false, 12) => 0,
            (true, hour) if hour != 12 => hour + 12,
            (_, hour) => hour,
        });
        Ok(())
    }

    /// A zone, which PHP lets be preceded by spaces and parentheses: `(CET)`.
    fn zone(&mut self) -> Result<(), ParseError> {
        let rest = self.rest();
        let text = rest.trim_start_matches([' ', '\t', '(']);
        let skipped = rest.len() - text.len();
        let mut open = rest[..skipped].matches('(').count();
        let Some((zone, length)) = Zone::scan(text) else {
            return self.error("The timezone could not be found in the database");
        };
        self.fields.identifier = matches!(zone, Zone::Named(_)) || &text[..length] == "UTC";
        self.fields.zone = Some(zone);
        self.position += skipped + length;
        while open > 0 && self.rest().starts_with(')') {
            self.position += 1;
            open -= 1;
        }
        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 || self.rest().starts_with('+'));
        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"))?;
        // Civil arithmetic: it reaches the end of the year 9999, further than jiff's `Timestamp`.
        let since = SignedDuration::from_secs(if negative { -seconds } else { seconds });
        let Ok(date) = EPOCH.checked_add(since) else {
            return self.error("A unix timestamp could not be found");
        };
        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));
        fields.identifier = false;
        Ok(())
    }

    /// Fill what the value left out from `now` and check that the result exists.
    fn finish(self, now: &PhpDateTime, disambiguation: Disambiguation) -> 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);
        }
        // A value that sets any date or time field has no microseconds unless it says so; one that only names a day
        // or a zone keeps those of `now`.
        // The hour is filled above when only a minute or a second was read.
        if fields.year.is_some() || fields.month.is_some() || fields.day.is_some() || fields.hour.is_some() {
            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_with(DateTime::from_parts(date, time), zone, disambiguation)
            .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()
}