parse_datetime 0.14.0

parsing human-readable time strings and converting them to a DateTime
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
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

use jiff::{civil, Span, ToSpan, Zoned};

use super::{date, epoch, error, offset, relative, time, weekday, year, Item};

/// The builder is used to construct a DateTime object from various components.
/// The parser creates a `DateTimeBuilder` object with the parsed components,
/// but without the baseline date and time. So you normally need to set the base
/// date and time using the `set_base()` method before calling `build()`, or
/// leave it unset to use the current date and time as the base.
#[derive(Debug, Default)]
pub(crate) struct DateTimeBuilder {
    base: Option<Zoned>,
    timestamp: Option<epoch::Timestamp>,
    date: Option<date::Date>,
    time: Option<time::Time>,
    weekday: Option<weekday::Weekday>,
    offset: Option<offset::Offset>,
    timezone: Option<jiff::tz::TimeZone>,
    relative: Vec<relative::Relative>,
}

impl DateTimeBuilder {
    pub(super) fn new() -> Self {
        Self::default()
    }

    /// Sets the base date and time for the builder. If not set, the current
    /// date and time will be used.
    pub(super) fn set_base(mut self, base: Zoned) -> Self {
        self.base = Some(base);
        self
    }

    /// Sets the timezone rule for the builder.
    ///
    /// By default, the builder uses the time zone rules indicated by the `TZ`
    /// environment variable, or the system default rules if `TZ` is not set.
    /// This method allows overriding the time zone rules.
    fn set_timezone(mut self, tz: jiff::tz::TimeZone) -> Result<Self, &'static str> {
        if self.timezone.is_some() {
            return Err("timezone rule cannot appear more than once");
        }

        self.timezone = Some(tz);
        Ok(self)
    }

    /// Sets a timestamp value. Timestamp values are exclusive to other date/time
    /// items (date, time, weekday, timezone, relative adjustments).
    pub(super) fn set_timestamp(mut self, ts: epoch::Timestamp) -> Result<Self, &'static str> {
        if self.timestamp.is_some() {
            return Err("timestamp cannot appear more than once");
        } else if self.date.is_some()
            || self.time.is_some()
            || self.weekday.is_some()
            || self.offset.is_some()
            || !self.relative.is_empty()
        {
            return Err("timestamp cannot be combined with other date/time items");
        }

        self.timestamp = Some(ts);
        Ok(self)
    }

    fn set_date(mut self, date: date::Date) -> Result<Self, &'static str> {
        if self.timestamp.is_some() {
            return Err("timestamp cannot be combined with other date/time items");
        } else if self.date.is_some() {
            return Err("date cannot appear more than once");
        }

        self.date = Some(date);
        Ok(self)
    }

    fn set_time(mut self, time: time::Time) -> Result<Self, &'static str> {
        if self.timestamp.is_some() {
            return Err("timestamp cannot be combined with other date/time items");
        } else if self.time.is_some() {
            return Err("time cannot appear more than once");
        } else if self.offset.is_some() && time.offset.is_some() {
            return Err("time offset and timezone are mutually exclusive");
        }

        self.time = Some(time);
        Ok(self)
    }

    fn set_weekday(mut self, weekday: weekday::Weekday) -> Result<Self, &'static str> {
        if self.timestamp.is_some() {
            return Err("timestamp cannot be combined with other date/time items");
        } else if self.weekday.is_some() {
            return Err("weekday cannot appear more than once");
        }

        self.weekday = Some(weekday);
        Ok(self)
    }

    fn set_offset(mut self, timezone: offset::Offset) -> Result<Self, &'static str> {
        if self.timestamp.is_some() {
            return Err("timestamp cannot be combined with other date/time items");
        } else if self.offset.is_some()
            || self.time.as_ref().and_then(|t| t.offset.as_ref()).is_some()
        {
            return Err("time offset cannot appear more than once");
        }

        self.offset = Some(timezone);
        Ok(self)
    }

    fn push_relative(mut self, relative: relative::Relative) -> Result<Self, &'static str> {
        if self.timestamp.is_some() {
            return Err("timestamp cannot be combined with other date/time items");
        }

        self.relative.push(relative);
        Ok(self)
    }

    /// Sets a pure number that can be interpreted as either a year or time
    /// depending on the current state of the builder.
    ///
    /// If a date is already set but lacks a year, the number is interpreted as
    /// a year. Otherwise, it's interpreted as a time in HHMM, HMM, HH, or H
    /// format.
    fn set_pure(mut self, pure: String) -> Result<Self, &'static str> {
        if self.timestamp.is_some() {
            return Err("timestamp cannot be combined with other date/time items");
        }

        if let Some(date) = self.date.as_mut() {
            if date.year.is_none() {
                date.year = Some(year::year_from_str(&pure)?);
                return Ok(self);
            }
        }

        let (mut hour_str, mut minute_str) = match pure.len() {
            1..=2 => (pure.as_str(), "0"),
            3..=4 => pure.split_at(pure.len() - 2),
            _ => {
                return Err("pure number must be 1-4 digits when interpreted as time");
            }
        };

        let hour = time::hour24(&mut hour_str).map_err(|_| "invalid hour in pure number")?;
        let minute = time::minute(&mut minute_str).map_err(|_| "invalid minute in pure number")?;

        let time = time::Time {
            hour,
            minute,
            ..Default::default()
        };
        self.set_time(time)
    }

    /// Build a `Zoned` object from the pieces accumulated in this builder.
    ///
    /// Resolution order (mirrors GNU `date` semantics):
    ///
    /// 1. Base instant.
    ///   - a. If `self.base` is provided, start with it.
    ///   - b. Else if a `timezone` rule is present, start with "now" in that
    ///     timezone.
    ///   - c. Else start with current system local time.
    ///
    /// 2. Absolute timestamp override.
    ///   - a. If `self.timestamp` is set, it fully determines the result.
    ///
    /// 3. Time of day truncation.
    ///   - a. If any of date, time, weekday, offset, timezone is set, zero the
    ///     time of day to 00:00:00 before applying fields.
    ///
    /// 4. Fieldwise resolution (applied to the base instant).
    ///   - a. Apply date. If year is absent in the parsed date, inherit the year
    ///     from the base instant.
    ///   - b. Apply time. If time carries an explicit numeric offset, apply the
    ///     offset before setting time.
    ///   - c. Apply weekday (e.g., "next Friday" or "last Monday").
    ///   - d. Apply relative adjustments (e.g., "+3 days", "-2 months").
    ///   - e. Apply final fixed offset if present.
    pub(super) fn build(self) -> Result<Zoned, error::Error> {
        // 1. Choose the base instant.
        // If a TZ="..." prefix was parsed, it should override the base's timezone
        // while keeping the base's timestamp for relative date calculations.
        let has_timezone = self.timezone.is_some();
        let base = match (self.base, self.timezone) {
            (Some(b), Some(tz)) => b.timestamp().to_zoned(tz),
            (Some(b), None) => b,
            (None, Some(tz)) => jiff::Timestamp::now().to_zoned(tz),
            (None, None) => Zoned::now(),
        };

        // 2. Absolute timestamp override everything else.
        if let Some(ts) = self.timestamp {
            let ts = jiff::Timestamp::try_from(ts)?;
            return Ok(ts.to_zoned(base.offset().to_time_zone()));
        }

        // 3. Determine whether to truncate the time of day.
        let need_midnight = self.date.is_some()
            || self.time.is_some()
            || self.weekday.is_some()
            || self.offset.is_some()
            || has_timezone;

        let mut dt = if need_midnight {
            base.with().time(civil::time(0, 0, 0, 0)).build()?
        } else {
            base
        };

        // 4a. Apply date.
        if let Some(date) = self.date {
            let d: civil::Date = if date.year.is_some() {
                date.try_into()?
            } else {
                date.with_year(dt.date().year() as u16).try_into()?
            };
            dt = dt.with().date(d).build()?;
        }

        // 4b. Apply time.
        if let Some(time) = self.time.clone() {
            if let Some(offset) = &time.offset {
                dt = dt.datetime().to_zoned(offset.try_into()?)?;
            }

            let t: civil::Time = time.try_into()?;
            dt = dt.with().time(t).build()?;
        }

        // 4c. Apply weekday.
        if let Some(weekday::Weekday { mut offset, day }) = self.weekday {
            if self.time.is_none() {
                dt = dt.with().time(civil::time(0, 0, 0, 0)).build()?;
            }

            let target = day.into();

            // If the current day is not the target day, we need to adjust
            // the x value to ensure we find the correct day.
            //
            // Consider this:
            // Assuming today is Monday, next Friday is actually THIS Friday;
            // but next Monday is indeed NEXT Monday.
            if dt.date().weekday() != target && offset > 0 {
                offset -= 1;
            }

            // Calculate the delta to the target day.
            //
            // Assuming today is Thursday, here are some examples:
            //
            // Example 1: last Thursday (x = -1, day = Thursday)
            //            delta = (3 - 3) % 7 + (-1) * 7 = -7
            //
            // Example 2: last Monday (x = -1, day = Monday)
            //            delta = (0 - 3) % 7 + (-1) * 7 = -3
            //
            // Example 3: next Monday (x = 1, day = Monday)
            //            delta = (0 - 3) % 7 + (0) * 7 = 4
            // (Note that we have adjusted the x value above)
            //
            // Example 4: next Thursday (x = 1, day = Thursday)
            //            delta = (3 - 3) % 7 + (1) * 7 = 7
            let delta = (target.since(civil::Weekday::Monday) as i32
                - dt.date().weekday().since(civil::Weekday::Monday) as i32)
                .rem_euclid(7)
                + offset.checked_mul(7).ok_or("multiplication overflow")?;

            dt = dt.checked_add(Span::new().try_days(delta)?)?;
        }

        // 4d. Apply relative adjustments.
        for rel in self.relative {
            dt = match rel {
                relative::Relative::Years(_) | relative::Relative::Months(_) => {
                    // GNU way of calculating relative months and years
                    // GNU changes the month and then checks if the target month has
                    // this day. If this day does not exist in the target month it overflows
                    // the difference
                    let original_day_of_month = dt.day();
                    dt = dt.checked_add::<Span>(rel.try_into()?)?;
                    if original_day_of_month != dt.day() {
                        dt = dt.checked_add(
                            (original_day_of_month.checked_sub(dt.day()).unwrap_or(0)).days(),
                        )?;
                    }
                    dt
                }
                _ => dt.checked_add::<Span>(rel.try_into()?)?,
            }
        }

        // 4e. Apply final fixed offset.
        if let Some(offset) = self.offset {
            let (offset, hour_adjustment) = offset.normalize();
            dt = dt.checked_add(Span::new().hours(hour_adjustment))?;
            dt = dt.datetime().to_zoned((&offset).try_into()?)?;
        }

        Ok(dt)
    }
}

impl TryFrom<Vec<Item>> for DateTimeBuilder {
    type Error = &'static str;

    fn try_from(items: Vec<Item>) -> Result<Self, Self::Error> {
        let mut builder = DateTimeBuilder::new();

        for item in items {
            builder = match item {
                Item::Timestamp(ts) => builder.set_timestamp(ts)?,
                Item::DateTime(dt) => builder.set_date(dt.date)?.set_time(dt.time)?,
                Item::Date(d) => builder.set_date(d)?,
                Item::Time(t) => builder.set_time(t)?,
                Item::Weekday(weekday) => builder.set_weekday(weekday)?,
                Item::Offset(offset) => builder.set_offset(offset)?,
                Item::Relative(rel) => builder.push_relative(rel)?,
                Item::TimeZone(tz) => builder.set_timezone(tz)?,
                Item::Pure(pure) => builder.set_pure(pure)?,
            }
        }

        Ok(builder)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Helper functions to create test items by parsing
    fn timestamp() -> epoch::Timestamp {
        let mut input = "@1234567890";
        epoch::parse(&mut input).unwrap()
    }

    fn date() -> date::Date {
        let mut input = "2023-06-15";
        date::parse(&mut input).unwrap()
    }

    fn time() -> time::Time {
        let mut input = "12:30:00";
        time::parse(&mut input).unwrap()
    }

    fn time_with_offset() -> time::Time {
        let mut input = "12:30:00+05:00";
        time::parse(&mut input).unwrap()
    }

    fn weekday() -> weekday::Weekday {
        let mut input = "monday";
        weekday::parse(&mut input).unwrap()
    }

    fn offset() -> offset::Offset {
        let mut input = "+05:00";
        offset::timezone_offset(&mut input).unwrap()
    }

    fn relative() -> relative::Relative {
        let mut input = "1 day";
        relative::parse(&mut input).unwrap()
    }

    fn timezone() -> jiff::tz::TimeZone {
        jiff::tz::TimeZone::UTC
    }

    #[test]
    fn test_duplicate_items_errors() {
        let test_cases = vec![
            (
                vec![Item::TimeZone(timezone()), Item::TimeZone(timezone())],
                "timezone rule cannot appear more than once",
            ),
            (
                vec![Item::Timestamp(timestamp()), Item::Timestamp(timestamp())],
                "timestamp cannot appear more than once",
            ),
            (
                vec![Item::Date(date()), Item::Date(date())],
                "date cannot appear more than once",
            ),
            (
                vec![Item::Time(time()), Item::Time(time())],
                "time cannot appear more than once",
            ),
            (
                vec![Item::Weekday(weekday()), Item::Weekday(weekday())],
                "weekday cannot appear more than once",
            ),
            (
                vec![Item::Offset(offset()), Item::Offset(offset())],
                "time offset cannot appear more than once",
            ),
        ];

        for (items, expected_err) in test_cases {
            let result = DateTimeBuilder::try_from(items);
            assert_eq!(result.unwrap_err(), expected_err);
        }
    }

    #[test]
    fn test_timestamp_cannot_be_combined_with_other_items() {
        let test_cases = vec![
            vec![Item::Date(date()), Item::Timestamp(timestamp())],
            vec![Item::Time(time()), Item::Timestamp(timestamp())],
            vec![Item::Weekday(weekday()), Item::Timestamp(timestamp())],
            vec![Item::Offset(offset()), Item::Timestamp(timestamp())],
            vec![Item::Relative(relative()), Item::Timestamp(timestamp())],
            vec![Item::Timestamp(timestamp()), Item::Date(date())],
            vec![Item::Timestamp(timestamp()), Item::Time(time())],
            vec![Item::Timestamp(timestamp()), Item::Weekday(weekday())],
            vec![Item::Timestamp(timestamp()), Item::Relative(relative())],
            vec![Item::Timestamp(timestamp()), Item::Offset(offset())],
            vec![Item::Timestamp(timestamp()), Item::Pure("2023".to_string())],
        ];

        for items in test_cases {
            let result = DateTimeBuilder::try_from(items);
            assert_eq!(
                result.unwrap_err(),
                "timestamp cannot be combined with other date/time items"
            );
        }
    }

    #[test]
    fn test_time_offset_conflicts() {
        // Time with offset followed by separate Offset item
        let items1 = vec![Item::Time(time_with_offset()), Item::Offset(offset())];
        assert_eq!(
            DateTimeBuilder::try_from(items1).unwrap_err(),
            "time offset cannot appear more than once"
        );

        // Offset item followed by Time with offset
        let items2 = vec![Item::Offset(offset()), Item::Time(time_with_offset())];
        assert_eq!(
            DateTimeBuilder::try_from(items2).unwrap_err(),
            "time offset and timezone are mutually exclusive"
        );
    }

    #[test]
    fn test_valid_combination_date_time() {
        let items = vec![Item::Date(date()), Item::Time(time())];
        let result = DateTimeBuilder::try_from(items);
        assert!(result.is_ok());
    }

    #[test]
    fn test_valid_combination_date_weekday() {
        let items = vec![Item::Date(date()), Item::Weekday(weekday())];
        let result = DateTimeBuilder::try_from(items);
        assert!(result.is_ok());
    }

    #[test]
    fn test_valid_timestamp_alone() {
        let items = vec![Item::Timestamp(timestamp())];
        let result = DateTimeBuilder::try_from(items);
        assert!(result.is_ok());
    }
}