hifitime 4.3.0

Ultra-precise date and time handling in Rust for scientific applications with leap second support
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/*
* Hifitime
* Copyright (C) 2017-onward Christopher Rabotin <christopher.rabotin@gmail.com> et al. (cf. https://github.com/nyx-space/hifitime/graphs/contributors)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Documentation: https://nyxspace.com/
*/

use snafu::ResultExt;

use super::formatter::Item;
use crate::errors::ParseSnafu;
use crate::{parser::Token, ParsingError};
use crate::{Epoch, HifitimeError, MonthName, TimeScale, Unit, Weekday};
use core::fmt;
use core::str::FromStr;

// Maximum number of tokens in a format.
const MAX_TOKENS: usize = 16;

/// Format allows formatting an Epoch with some custom arrangement of the Epoch items.
/// This provides almost all of the options from the 1989 C standard.
///
/// Construct a format with `Format::from_str` (no allocation needed) where the string
/// contains a succession of tokens (each starting with `%`) and up to two separators between tokens.
///
/// Then this format can then be provided to the `Formatter` for formatting. This is also no-std.
///
/// # Supported tokens
///
/// Any token may be followed by `?` to make it optional. For integer values, an optional token will only be printed
/// if its value is non-zero. For time scales, only non-UTC time scale will be printed.
///
/// ## C89 standard tokens
///
/// | Token | Explanation | Example | Notes
/// | :-- | :-- | :-- | :-- |
/// | `%Y` | Proleptic Gregorian year, zero-padded to 4 digits | `2022` | (1) |
/// | `%y` | Proleptic Gregorian year after 2000, on two digits | `23` | N/A |
/// | `%m` | Month number, zero-padded to 2 digits | `03` for March | N/A |
/// | `%b` | Month name in short form | `Mar` for March | N/A |
/// | `%B` | Month name in long form | `March` | N/A |
/// | `%d` | Day number, zero-padded to 2 digits | `07` for the 7th day of the month | N/A |
/// | `%j` | Day of year, zero-padded to 3 digits | `059` for 29 February 2000 | N/A |
/// | `%A` | Weekday name in long form | `Monday` | N/A |
/// | `%a` | Weekday name in short form | `Mon` for Monday | N/A |
/// | `%H` | Hour number, zero-padded to 2 digits | `02` for the 2nd hour of the day | N/A |
/// | `%M` | Minute number, zero-padded to 2 digits | `39` for the 39th minutes of the hour | N/A |
/// | `%S` | Seconds, zero-padded to 2 digits | `27` for the 27th second of the minute | N/A |
/// | `%f` | Sub-seconds, zero-padded to 9 digits | `000000007` for the 7th nanosecond past the second | (2) |
/// | `%w` | Weekday in decimal form with C89 standard | `01` for Dynamical barycentric time | (3) |
/// | `%z` | Offset timezone if the formatter is provided with an epoch. | `+15:00` For GMT +15 hours and zero minutes | N/A |
///
/// * (1): Hifitime supports years from -34668 to 34668. If your epoch is larger than +/- 9999 years, the formatting of the years _will_ show all five digits of the year.
/// * (2): Hifitime supports exactly nanosecond precision, and this is not lost when formatting.
///
/// ## Hifitime specific tokens
///
/// These are chosen to not conflict with strptime/strfime of the C89 standard.
/// | Token | Explanation | Example | Notes
/// | :-- | :-- | :-- | :-- |
/// | `%T` | Time scale used to represent this date | `TDB` for Dynamical barycentric time | (3) |
/// | `%J` | Full day of year as a double | `59.62325231481524` for 29 February 2000 14:57:29 UTC | N/A |
///
/// * (3): Hifitime supports many time scales and these should not be lost when formatting. **This is a novelty compared to other time management libraries** as most do not have any concept of time scales.
///
///
/// # Example
/// ```
/// use hifitime::prelude::*;
/// use hifitime::efmt;
/// use hifitime::efmt::consts;
/// use core::str::FromStr;
///
/// let bday = Epoch::from_gregorian_utc(2000, 2, 29, 14, 57, 29, 37);
///
/// let fmt = efmt::Format::from_str("%Y-%m-%d").unwrap();
/// assert_eq!(fmt, consts::ISO8601_DATE);
///
/// let fmtd_bday = Formatter::new(bday, fmt);
/// assert_eq!(format!("{fmtd_bday}"), format!("2000-02-29"));
///
/// let fmt = Format::from_str("%Y-%m-%dT%H:%M:%S.%f %T").unwrap();
/// assert_eq!(fmt, consts::ISO8601);
///
/// let fmtd_bday = Formatter::new(bday, fmt);
/// // ISO with the timescale is the default format
/// assert_eq!(format!("{fmtd_bday}"), format!("{bday}"));
///
/// let fmt = Format::from_str("%Y-%j").unwrap();
/// assert_eq!(fmt, consts::ISO8601_ORDINAL);
///
/// let fmt_iso_ord = Formatter::new(bday, consts::ISO8601_ORDINAL);
/// assert_eq!(format!("{fmt_iso_ord}"), "2000-060");
///
/// let fmt = Format::from_str("%A, %d %B %Y %H:%M:%S").unwrap();
/// assert_eq!(fmt, consts::RFC2822_LONG);
///
/// let fmt = Formatter::new(bday, consts::RFC2822_LONG);
/// assert_eq!(
///     format!("{fmt}"),
///     format!("Tuesday, 29 February 2000 14:57:29")
/// );
///
/// let fmt = Format::from_str("%a, %d %b %Y %H:%M:%S").unwrap();
/// assert_eq!(fmt, consts::RFC2822);
///
/// let fmt = Formatter::new(bday, consts::RFC2822);
/// assert_eq!(format!("{fmt}"), format!("Tue, 29 Feb 2000 14:57:29"));
/// ```
#[cfg_attr(kani, derive(kani::Arbitrary))]
#[derive(Copy, Clone, Default, PartialEq)]
pub struct Format {
    pub(crate) items: [Option<Item>; MAX_TOKENS],
    pub(crate) num_items: usize,
}

impl Format {
    pub(crate) fn need_gregorian(&self) -> bool {
        let mut i: usize = 0;
        #[cfg_attr(kani, kani::loop_invariant(i <= self.num_items && i <= MAX_TOKENS))]
        while i < self.num_items && i < MAX_TOKENS {
            if let Some(item) = self.items[i].as_ref() {
                match item.token {
                    Token::Year
                    | Token::YearShort
                    | Token::Month
                    | Token::MonthName
                    | Token::MonthNameShort
                    | Token::Day
                    | Token::Hour
                    | Token::Minute
                    | Token::Second
                    | Token::Subsecond
                    | Token::OffsetHours
                    | Token::OffsetMinutes => return true,
                    Token::Timescale
                    | Token::DayOfYearInteger
                    | Token::DayOfYear
                    | Token::Weekday
                    | Token::WeekdayShort
                    | Token::WeekdayDecimal => {
                        // These tokens don't need the gregorian, but other tokens in the list of tokens might.
                    }
                }
            }
            i += 1;
        }
        false
    }

    pub fn parse(&self, s_in: &str) -> Result<Epoch, HifitimeError> {
        // All of the integers in a date: year, month, day, hour, minute, second, subsecond, offset hours, offset minutes
        let mut decomposed = [0_i32; MAX_TOKENS];
        // The parsed time scale, defaults to UTC
        let mut ts = TimeScale::UTC;
        // The offset sign, defaults to positive.
        let mut offset_sign = 1;
        let mut day_of_year: Option<f64> = None;
        let mut weekday: Option<Weekday> = None;

        // Previous index of interest in the string
        let mut prev_idx = 0;
        let mut cur_item_idx = 0;
        let mut cur_item = match self.items[cur_item_idx] {
            Some(item) => item,
            None => {
                return Err(HifitimeError::Parse {
                    source: ParsingError::NothingToParse,
                    details: "format string contains no tokens",
                })
            }
        };
        let mut cur_token = cur_item.token;
        let mut prev_item = cur_item;
        let mut prev_token;

        let s = s_in.trim();

        for (idx, char) in s.char_indices() {
            let reached_fixed_length = cur_item.sep_char.is_none()
                && cur_item.second_sep_char.is_none()
                && !cur_item.optional
                && cur_token
                    .fixed_length()
                    .map(|l| idx >= prev_idx && idx - prev_idx + 1 == l)
                    .unwrap_or(false);

            // We should parse if:
            // 1. we're at the end of the string
            // 2. Or we've hit a non-numeric char and the token is fully numeric
            // 3. Or, token is not numeric (e.g. month name) and the current char is the separator
            // 4. Or, we've reached the fixed length of the token and there are no separators
            // 5. And, if the length of the current substring is longer than 1 and the char is not the optional separator of the previous token.
            if idx == s.len() - 1
                || ((cur_token.is_numeric() && !char.is_numeric())
                    || (!cur_token.is_numeric() && (cur_item.sep_char_is(char))))
                || reached_fixed_length
            {
                // If we've found the second separator of the previous token, let's simply increment the start index of the next substring.
                if idx == prev_idx
                    && (prev_item.second_sep_char.is_none() || prev_item.second_sep_char_is(char))
                    && !reached_fixed_length
                {
                    prev_idx += 1;
                    continue;
                }

                if cur_token == Token::Timescale {
                    // Then we match the timescale directly.
                    if idx != s.len() - 1 {
                        // We have some remaining characters, so let's parse those in the only formats we know.
                        ts = TimeScale::from_str(s[idx..].trim()).with_context(|_| ParseSnafu {
                            details: "when parsing from format string",
                        })?;
                    }
                    break;
                } else if char == 'Z' {
                    // This is a single character to represent UTC
                    // UTC is the default time scale, so we don't need to do anything.
                    break;
                }
                prev_item = cur_item;
                prev_token = cur_token;

                let end_idx = if reached_fixed_length {
                    // Advance the token, unless we're at the end of the tokens.
                    if cur_item_idx < self.num_items {
                        cur_item_idx += 1;
                        if let Some(item) = self.items[cur_item_idx] {
                            cur_item = item;
                            cur_token = cur_item.token;
                        }
                    }
                    idx + 1
                } else if idx != s.len() - 1 || !char.is_numeric() {
                    // Only advance the token if we aren't at the end of the string
                    if !reached_fixed_length
                        && cur_item.sep_char_is_not(char)
                        && (cur_item.second_sep_char.is_none()
                            || (cur_item.second_sep_char_is_not(char)))
                    {
                        return Err(HifitimeError::Parse {
                            source: ParsingError::UnexpectedCharacter {
                                found: char,
                                option1: cur_item.sep_char,
                                option2: cur_item.second_sep_char,
                            },
                            details: "when parsing from format string",
                        });
                    }

                    // Advance the token, unless we're at the end of the tokens.
                    if cur_item_idx == self.num_items {
                        break;
                    }
                    cur_item_idx += 1;
                    match self.items[cur_item_idx] {
                        Some(item) => {
                            cur_item = item;
                            cur_token = cur_item.token;
                        }
                        None => break,
                    }

                    idx
                } else {
                    idx + 1
                };

                let sub_str = &s[prev_idx..end_idx];

                match prev_token {
                    Token::YearShort => {
                        decomposed[0] =
                            sub_str.parse::<i32>().map_err(|_| HifitimeError::Parse {
                                source: ParsingError::ValueError,
                                details: "could not parse year as i32",
                            })? + 2000;
                    }
                    Token::DayOfYear => {
                        // We must parse this as a floating point value.
                        match lexical_core::parse(sub_str.as_bytes()) {
                            Ok(val) => day_of_year = Some(val),
                            Err(_) => {
                                return Err(HifitimeError::Parse {
                                    source: ParsingError::ValueError,
                                    details: "could not parse day of year as f64",
                                })
                            }
                        }
                    }
                    Token::Weekday | Token::WeekdayShort => {
                        // Set the weekday
                        match Weekday::from_str(sub_str) {
                            Ok(day) => weekday = Some(day),
                            Err(source) => {
                                return Err(HifitimeError::Parse {
                                    source,
                                    details: "could not parse weekday",
                                })
                            }
                        }
                    }
                    Token::WeekdayDecimal => {
                        todo!()
                    }
                    Token::MonthName | Token::MonthNameShort => {
                        match MonthName::from_str(sub_str) {
                            Ok(month) => {
                                decomposed[1] = ((month as u8) + 1) as i32;
                            }
                            Err(_) => {
                                return Err(HifitimeError::Parse {
                                    source: ParsingError::ValueError,
                                    details: "could not parse month name",
                                })
                            }
                        }
                    }
                    _ => {
                        match lexical_core::parse(sub_str.as_bytes()) {
                            Ok(val) => {
                                // Check that this valid is OK for the token we're reading it as.
                                prev_token.value_ok(val)?;
                                match prev_token.gregorian_position() {
                                    Some(pos) => {
                                        // If these are the subseconds, we must convert them to nanoseconds
                                        if prev_token == Token::Subsecond {
                                            if end_idx - prev_idx != 9 {
                                                decomposed[pos] = val
                                                    * 10_i32.pow((9 - (end_idx - prev_idx)) as u32);
                                            } else {
                                                decomposed[pos] = val;
                                            }
                                        } else {
                                            decomposed[pos] = val
                                        }
                                    }
                                    None => match prev_token {
                                        Token::DayOfYearInteger => day_of_year = Some(val as f64),
                                        Token::Weekday => todo!(),
                                        Token::WeekdayShort => todo!(),
                                        Token::WeekdayDecimal => todo!(),
                                        Token::MonthName => todo!(),
                                        Token::MonthNameShort => todo!(),
                                        _ => unreachable!(),
                                    },
                                }
                            }
                            Err(err) => {
                                return Err(HifitimeError::Parse {
                                    source: ParsingError::Lexical { err },
                                    details: "could not parse numerical",
                                });
                            }
                        }
                    }
                }

                prev_idx = idx + 1;
                // If we are about to parse an hours offset, we need to set the sign now.
                if cur_token == Token::OffsetHours {
                    let sign_idx = if reached_fixed_length { idx + 1 } else { idx };
                    if sign_idx < s.len() && &s[sign_idx..sign_idx + 1] == "-" {
                        offset_sign = -1;
                    }
                    prev_idx += 1;
                }
            }
        }

        let tz = if offset_sign > 0 {
            // We oppose the sign in the string to undo the offset
            -(i64::from(decomposed[7]) * Unit::Hour + i64::from(decomposed[8]) * Unit::Minute)
        } else {
            i64::from(decomposed[7]) * Unit::Hour + i64::from(decomposed[8]) * Unit::Minute
        };

        let epoch = match day_of_year {
            Some(days) => {
                // Parse the elapsed time in the given day
                let elapsed = (decomposed[3] as i64) * Unit::Hour
                    + (decomposed[4] as i64) * Unit::Minute
                    + (decomposed[5] as i64) * Unit::Second
                    + (decomposed[6] as i64) * Unit::Nanosecond;
                Epoch::from_day_of_year(decomposed[0], days, ts) + elapsed
            }
            None => Epoch::maybe_from_gregorian(
                decomposed[0],
                decomposed[1].try_into().unwrap(),
                decomposed[2].try_into().unwrap(),
                decomposed[3].try_into().unwrap(),
                decomposed[4].try_into().unwrap(),
                decomposed[5].try_into().unwrap(),
                decomposed[6].try_into().unwrap(),
                ts,
            )?,
        };

        if let Some(weekday) = weekday {
            // Check that the weekday is correct
            if weekday != epoch.weekday() {
                return Err(HifitimeError::Parse {
                    source: ParsingError::WeekdayMismatch {
                        found: weekday,
                        expected: epoch.weekday(),
                    },
                    details: "weekday and day number do not match",
                });
            }
        }

        Ok(epoch + tz)
    }
}

impl fmt::Debug for Format {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "EpochFormat:`")?;
        for maybe_item in self.items.iter().take(self.num_items) {
            let item = maybe_item.as_ref().unwrap();
            write!(f, "{:?}", item.token)?;
            if let Some(char) = item.sep_char {
                write!(f, "{char}")?;
            }
            if let Some(char) = item.second_sep_char {
                write!(f, "{char}")?;
            }
            if item.optional {
                write!(f, "?")?;
            }
        }
        write!(f, "`")?;
        Ok(())
    }
}

impl FromStr for Format {
    type Err = ParsingError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut me = Format::default();
        for token in s.split('%') {
            if me.num_items == MAX_TOKENS && token.chars().next().is_some() {
                return Err(ParsingError::UnknownFormat);
            }
            match token.chars().next() {
                Some(char) => match char {
                    'Y' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::Year,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'y' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::YearShort,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'm' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::Month,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'b' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::MonthNameShort,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'B' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::MonthName,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'd' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::Day,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'j' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::DayOfYearInteger,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'J' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::DayOfYear,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'A' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::Weekday,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'a' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::WeekdayShort,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'H' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::Hour,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'M' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::Minute,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'S' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::Second,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'f' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::Subsecond,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'T' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::Timescale,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'w' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::WeekdayDecimal,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    'z' => {
                        me.items[me.num_items] = Some(Item::new(
                            Token::OffsetHours,
                            token.chars().nth(1),
                            token.chars().nth(2),
                        ));
                        me.num_items += 1;
                    }
                    _ => return Err(ParsingError::UnknownToken { token: char }),
                },
                None => continue, // We're probably just at the start of the string
            }
        }

        Ok(me)
    }
}

#[test]
fn epoch_format_from_str() {
    let fmt = Format::from_str("%Y-%m-%d").unwrap();
    assert_eq!(fmt, crate::efmt::consts::ISO8601_DATE);

    let fmt = Format::from_str("%Y-%m-%dT%H:%M:%S.%f %T").unwrap();
    assert_eq!(fmt, crate::efmt::consts::ISO8601);

    let fmt = Format::from_str("%Y-%m-%dT%H:%M:%S.%f? %T?").unwrap();
    assert_eq!(fmt, crate::efmt::consts::ISO8601_FLEX);

    let fmt = Format::from_str("%Y-%j").unwrap();
    assert_eq!(fmt, crate::efmt::consts::ISO8601_ORDINAL);

    let fmt = Format::from_str("%A, %d %B %Y %H:%M:%S").unwrap();
    assert_eq!(fmt, crate::efmt::consts::RFC2822_LONG);

    let fmt = Format::from_str("%a, %d %b %Y %H:%M:%S").unwrap();
    assert_eq!(fmt, crate::efmt::consts::RFC2822);
}

#[cfg(feature = "std")]
#[test]
fn gh_248_regression() {
    /*
    Update on 2023-12-30 to match the Python behavior:

    >>> from datetime import datetime
    >>> dt, fmt = "2023-117T12:55:26", "%Y-%jT%H:%M:%S"
    >>> datetime.strptime(dt, fmt)
    datetime.datetime(2023, 4, 27, 12, 55, 26)
     */

    let e = Epoch::from_format_str("2023-117T12:55:26", "%Y-%jT%H:%M:%S").unwrap();

    assert_eq!(format!("{e}"), "2023-04-27T12:55:26 UTC");
}

#[cfg(feature = "std")]
#[test]
fn test_strptime_no_separators() {
    let fmt = Format::from_str("%Y%m%d%H%M%S").unwrap();
    let e = fmt.parse("20270216143714").unwrap();
    assert_eq!(format!("{e}"), "2027-02-16T14:37:14 UTC");

    let fmt = Format::from_str("%Y%m%d").unwrap();
    let e = fmt.parse("20230102").unwrap();
    assert_eq!(format!("{e}"), "2023-01-02T00:00:00 UTC");
}