use super::*;
fn utc(s: &str) -> Timestamp {
s.parse().unwrap()
}
fn plus_ten() -> TimeDefaults {
TimeDefaults {
zone: TimeZone::fixed(Offset::from_hours(10).unwrap()),
year: Some(2026),
now: None,
..TimeDefaults::default()
}
}
#[test]
fn each_format_reads_to_the_right_instant() {
let rows: &[(TimeFormat, &str, &str)] = &[
(
TimeFormat::Iso8601,
"2026-11-26T11:22:33.456+11:00",
"2026-11-26T00:22:33.456Z",
),
(
TimeFormat::Iso8601,
"2026-11-26 11:22:33,5Z",
"2026-11-26T11:22:33.5Z",
),
(
TimeFormat::Iso8601,
"2026-11-26T11:22+1100",
"2026-11-26T00:22:00Z",
),
(
TimeFormat::Iso8601,
"2026-11-26T11:22:33",
"2026-11-26T01:22:33Z",
),
(
TimeFormat::Iso8601,
"2026-11-26T11:22:33-05:30",
"2026-11-26T16:52:33Z",
),
(
TimeFormat::Iso8601,
"2026-11-26t11:22:33.5z",
"2026-11-26T11:22:33.5Z",
),
(
TimeFormat::Iso8601,
"2026-11-26T11:22:33+11",
"2026-11-26T00:22:33Z",
),
(
TimeFormat::Iso8601,
"2026-11-26 11:22:33.1234567891234-01",
"2026-11-26T12:22:33.123456789Z",
),
(
TimeFormat::HttpDate,
"26/Nov/2026:11:22:33 +1100",
"2026-11-26T00:22:33Z",
),
(
TimeFormat::HttpDate,
"6/June/2026:01:02:03 -0000",
"2026-06-06T01:02:03Z",
),
(
TimeFormat::Syslog,
"Nov 6 08:01:02",
"2026-11-05T22:01:02Z",
),
(
TimeFormat::Syslog,
"Jan 15 23:59:59.25",
"2026-01-15T13:59:59.25Z",
),
(
TimeFormat::Epoch(EpochUnit::Seconds),
"1764116553",
"2025-11-26T00:22:33Z",
),
(
TimeFormat::Epoch(EpochUnit::Seconds),
"1764116553.5",
"2025-11-26T00:22:33.5Z",
),
(
TimeFormat::Epoch(EpochUnit::Millis),
"1764116553123",
"2025-11-26T00:22:33.123Z",
),
(
TimeFormat::Epoch(EpochUnit::Micros),
"-1000000",
"1969-12-31T23:59:59Z",
),
(
TimeFormat::Epoch(EpochUnit::Nanos),
"1",
"1970-01-01T00:00:00.000000001Z",
),
(
TimeFormat::Rfc2822,
"Thu, 26 Nov 2026 11:22:33 +1100",
"2026-11-26T00:22:33Z",
),
(
TimeFormat::Strptime("%d/%b/%Y:%H:%M:%S %z".into()),
"26/Nov/2026:11:22:33 +1100",
"2026-11-26T00:22:33Z",
),
(
TimeFormat::Strptime("%Y%m%d %H%M%S".into()),
"20261126 112233",
"2026-11-26T01:22:33Z",
),
];
for (format, input, want) in rows {
let got = parse_time(format, input.as_bytes(), &plus_ten()).unwrap();
assert_eq!(got, utc(want), "{format:?} {input:?}");
}
}
#[test]
fn a_stamp_keeps_the_offset_its_text_named() {
let rows: &[(TimeFormat, &str, Option<i32>, &str)] = &[
(
TimeFormat::Iso8601,
"2026-11-30T10:00:00+10:00",
Some(36_000),
"2026-11-30T10:00:00+10:00",
),
(
TimeFormat::Iso8601,
"2026-11-30T10:00:00",
None,
"2026-11-30T00:00:00Z",
),
(
TimeFormat::Iso8601,
"2026-11-30t10:00:00.25z",
Some(0),
"2026-11-30T10:00:00.25Z",
),
(
TimeFormat::Iso8601,
"2026-11-30 10:00-0530",
Some(-19_800),
"2026-11-30T10:00:00-05:30",
),
(
TimeFormat::Iso8601,
"2026-11-30T10:00:00-00",
Some(0),
"2026-11-30T10:00:00Z",
),
(
TimeFormat::HttpDate,
"30/Nov/2026:10:00:00 +1100",
Some(39_600),
"2026-11-30T10:00:00+11:00",
),
(
TimeFormat::Syslog,
"Nov 30 10:00:00",
None,
"2026-11-30T00:00:00Z",
),
(
TimeFormat::Rfc2822,
"Mon, 30 Nov 2026 10:00:00 -0800",
Some(-28_800),
"2026-11-30T10:00:00-08:00",
),
(
TimeFormat::Strptime("%Y-%m-%d %H:%M %z".into()),
"2026-11-30 10:00 +0930",
Some(34_200),
"2026-11-30T10:00:00+09:30",
),
(
TimeFormat::Strptime("%Y-%m-%d %H:%M".into()),
"2026-11-30 10:00",
None,
"2026-11-30T00:00:00Z",
),
(
TimeFormat::Strptime("%s".into()),
"1796032800",
Some(0),
"2026-11-30T10:00:00Z",
),
(
TimeFormat::Epoch(EpochUnit::Auto),
"1796032800000",
Some(0),
"2026-11-30T10:00:00Z",
),
(
TimeFormat::Tai64n,
"@400000006b0d492a00000000",
Some(0),
"2026-11-30T10:00:00Z",
),
(
java("yyyy-MM-dd HH:mm z"),
"2026-11-30 10:00 AEDT",
Some(39_600),
"2026-11-30T10:00:00+11:00",
),
(
java("yyyy-MM-dd HH:mm[ XXX]"),
"2026-11-30 10:00",
None,
"2026-11-30T00:00:00Z",
),
(
java("yyyy-MM-dd HH:mm[ XXX]"),
"2026-11-30 10:00 Z",
Some(0),
"2026-11-30T10:00:00Z",
),
];
let written = RenderFormat::Rfc3339(Fraction::Trimmed(0));
let failed: Vec<String> = rows
.iter()
.filter_map(|(format, input, secs, text)| {
let got = parse_stamp(format, input.as_bytes(), &plus_ten());
let want_offset = secs.map(|s| Offset::from_seconds(s).unwrap());
let ok = got.as_ref().is_ok_and(|stamp| {
stamp.offset == want_offset
&& render(stamp.timestamp, &written, &stamp.zone_or(&TimeZone::UTC))
.ok()
.as_deref()
== Some(*text)
});
(!ok).then(|| format!("{format:?} {input:?}: {got:?}, want {secs:?} {text}"))
})
.collect();
assert!(failed.is_empty(), "{failed:#?}");
let listed = [TimeFormat::Epoch(EpochUnit::Seconds), TimeFormat::Iso8601];
let got = parse_stamp_any(&listed, b"2026-11-30T10:00:00", &plus_ten()).unwrap();
assert_eq!(
(got.offset, got.timestamp),
(None, utc("2026-11-30T00:00:00Z"))
);
}
#[test]
fn iso8601_reads_and_refuses_as_the_loader_does() {
let d = TimeDefaults::default();
let zoned = [
"2026-04-07T17:03:00.123456789+10:00",
"2026-04-07T17:03:00.123456789+1000",
"2026-04-07T17:03:00.123456789+10",
"2026-04-07T01:33:00.123456789-05:30",
"2026-04-07 07:03:00.123456789Z",
"2026-04-07t07:03:00.123456789z",
"2026-04-07T07:03:00.123456789+00:00",
"2026-04-07T07:03:00.123456789-00:00",
];
for text in zoned {
let got = parse_stamp(&TimeFormat::Iso8601, text.as_bytes(), &d).unwrap();
assert_eq!(
got.timestamp,
utc("2026-04-07T07:03:00.123456789Z"),
"{text}"
);
assert!(got.offset.is_some(), "{text}");
}
for text in ["2026-04-07 07:03:00", "2026-04-07T07:03:00"] {
let got = parse_stamp(&TimeFormat::Iso8601, text.as_bytes(), &d).unwrap();
assert_eq!(
(got.timestamp, got.offset),
(utc("2026-04-07T07:03:00Z"), None)
);
}
let refused: &[(&str, &str)] = &[
("", "Shape"),
("2026-04-07", "Shape"),
("2026-04-07X07:03:00", "Shape"),
("2026-13-07 07:03:00", "Range"),
("2026-02-29 07:03:00", "Range"),
("2026-04-31 07:03:00", "Range"),
("2026-04-07 24:00:00", "Range"),
("2026-04-07 07:03:60", "Range"),
("2026-04-07 07:03:61", "Shape"),
("2026-04-07 07:03:", "Shape"),
("2026-04-07 07:03:00.", "Shape"),
("2026-04-07 07:03:00+24:00", "Shape"),
("2026-04-07 07:03:00+10:60", "Shape"),
("2026-04-07 07:03:00+1", "Shape"),
("2026-04-07 07:03:00+10:", "Shape"),
("2026-04-07 07:03:00+10:00 ", "Shape"),
("2026-04-07 07:03:00Zz", "Shape"),
("2026-04-07 07:03:00 UTC", "Shape"),
("2026-1\u{e9}-7 07:03:00", "Shape"),
(
"\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}",
"Shape",
),
];
for &(text, want) in refused {
let kind = match parse_stamp(&TimeFormat::Iso8601, text.as_bytes(), &d) {
Err(TimeError::Shape(_)) => "Shape",
Err(TimeError::Range(_)) => "Range",
other => panic!("{text:?}: {other:?}"),
};
assert_eq!(kind, want, "{text:?}");
}
assert!(parse_time(&TimeFormat::Iso8601, b"2024-02-29 07:03:00", &d).is_ok());
}
#[test]
fn common_shapes_read_with_a_declared_format() {
let d = TimeDefaults {
zone: TimeZone::UTC,
year: Some(2026),
now: None,
..TimeDefaults::default()
};
let rows: &[(&str, &str, &str)] = &[
(
"%Y-%m-%d %H:%M:%S%:::z",
"2019-11-29 08:08:05-08",
"2019-11-29T16:08:05Z",
),
(
"%Y-%m-%d %H:%M%:::z",
"2019-11-29 08:08-08",
"2019-11-29T16:08:00Z",
),
(
"%Y-%m-%d %H:%M:%S%.f%:::z",
"2021-05-02 23:31:36.0741-07",
"2021-05-03T06:31:36.0741Z",
),
(
"%Y-%m-%d %H:%M:%S%:::z",
"2021-05-02 23:31:36+05:30",
"2021-05-02T18:01:36Z",
),
(
"%Y-%m-%d %I:%M:%S %p",
"2014-04-26 05:24:37 PM",
"2014-04-26T17:24:37Z",
),
(
"%Y-%m-%d %H:%M:%S %:z",
"2014-04-26 13:13:44 +09:00",
"2014-04-26T04:13:44Z",
),
(
"%Y-%m-%d %H:%M:%S %z",
"2014-04-26 13:13:43 +0800",
"2014-04-26T05:13:43Z",
),
(
"%Y-%m-%d %H:%M:%S%.f %z",
"2012-08-03 18:31:59.257000000 +0000",
"2012-08-03T18:31:59.257Z",
),
(
"%Y-%m-%d %H:%M:%S UTC",
"2014-12-16 06:20:00 UTC",
"2014-12-16T06:20:00Z",
),
("%Y-%m-%d", "2021-02-21", "2021-02-21T00:00:00Z"),
(
"%B %d, %Y %I:%M:%S %p",
"May 8, 2009 5:57:51 PM",
"2009-05-08T17:57:51Z",
),
(
"%B %d, %Y %I:%M%p",
"September 17, 2012 10:09am",
"2012-09-17T10:09:00Z",
),
(
"%B %d, %Y, %H:%M:%S",
"September 17, 2012, 10:10:09",
"2012-09-17T10:10:09Z",
),
("%b %d, %Y", "oct 7, 1970", "1970-10-07T00:00:00Z"),
("%b. %d, %y", "oct. 7, 70", "1970-10-07T00:00:00Z"),
("%Y-%b-%d", "2021-Feb-21", "2021-02-21T00:00:00Z"),
(
"%d %b %Y %H:%M:%S%.f",
"14 May 2019 19:11:40.164",
"2019-05-14T19:11:40.164Z",
),
(
"%d %b %Y, %H:%M",
"12 Feb 2006, 19:17",
"2006-02-12T19:17:00Z",
),
("%d %B %Y", "03 February 2013", "2013-02-03T00:00:00Z"),
("%m/%d/%y %H:%M", "4/8/14 22:05", "2014-04-08T22:05:00Z"),
(
"%m/%d/%Y %I:%M:%S %p",
"8/8/1965 12:00:00 AM",
"1965-08-08T00:00:00Z",
),
(
"%m/%d/%Y %H:%M:%S%.f",
"03/19/2012 10:11:59.3186369",
"2012-03-19T10:11:59.3186369Z",
),
(
"%Y/%m/%d %H:%M:%S",
"2014/4/02 03:00:51",
"2014-04-02T03:00:51Z",
),
("%m.%d.%y", "08.21.71", "1971-08-21T00:00:00Z"),
("%b %d %H:%M:%S", "May 27 02:45:27", "2026-05-27T02:45:27Z"),
];
let failed: Vec<String> = rows
.iter()
.filter_map(|(fmt, input, want)| {
let got = parse_time(&TimeFormat::Strptime((*fmt).into()), input.as_bytes(), &d);
(got.as_ref().ok() != Some(&utc(want))).then(|| format!("{fmt:?} {input:?}: {got:?}"))
})
.collect();
assert!(failed.is_empty(), "{failed:#?}");
}
#[test]
fn other_tools_formats_translate_to_the_right_instant() {
use StrptimeDialect::{Ctime, Jiff, PercentL, PercentN};
let d = TimeDefaults {
zone: TimeZone::UTC,
year: Some(2026),
now: None,
..TimeDefaults::default()
};
let rows: &[(StrptimeDialect, &str, &str, &str)] = &[
(
PercentL,
"%Y-%m-%dT%H:%M:%S.%L%z",
"2026-11-26T11:22:33.456+1100",
"2026-11-26T00:22:33.456Z",
),
(
Ctime,
"%Y-%m-%d %H:%M:%S.%L %j",
"2026-11-26 11:22:33.5 +11:00",
"2026-11-26T00:22:33.5Z",
),
(
Ctime,
"%q/%g/%Y %l:%M %p",
"11/6/2026 3:04 PM",
"2026-11-06T15:04:00Z",
),
(
Ctime,
"%o/%d/%Y %H:%M:%S %i",
" 1/02/2026 10:00:00 -05",
"2026-01-02T15:00:00Z",
),
(
Ctime,
"%D %T %w",
"01/02/2026 10:00:00 +053000",
"2026-01-02T04:30:00Z",
),
(
Ctime,
"%c",
"Mon Jan 05 15:04:05 2026",
"2026-01-05T15:04:05Z",
),
(
PercentN,
"%Y-%m-%d %H:%M:%S.%3N %z",
"2026-11-26 11:22:33.123 -0500",
"2026-11-26T16:22:33.123Z",
),
(
PercentN,
"%d/%m/%Y %H:%M:%S.%Q",
"26/11/2026 11:22:33.250",
"2026-11-26T11:22:33.25Z",
),
(
PercentN,
"%s.%6N",
"1764116553.123456",
"2025-11-26T00:22:33.123456Z",
),
(Jiff, "%Y %j", "2026 060", "2026-03-01T00:00:00Z"),
(Jiff, "%s.%f", "-1.5", "1969-12-31T23:59:58.5Z"),
];
let failed: Vec<String> = rows
.iter()
.filter_map(|&(dialect, fmt, input, want)| {
let got = TimeFormat::strptime(dialect, fmt)
.and_then(|f| parse_time(&f, input.as_bytes(), &d));
(got.as_ref().ok() != Some(&utc(want)))
.then(|| format!("{dialect:?} {fmt:?} {input:?}: {got:?}"))
})
.collect();
assert!(failed.is_empty(), "{failed:#?}");
let refused = |dialect, fmt| match TimeFormat::strptime(dialect, fmt) {
Err(TimeError::Directive(spec)) => spec,
other => panic!("{fmt}: {other:?}"),
};
assert_eq!(refused(PercentN, "%Y %Z"), "%Z");
assert_eq!(refused(PercentN, "%s %Ez"), "%E");
assert_eq!(refused(PercentN, "%c"), "%c");
assert_eq!(refused(PercentL, "%H:%M %"), "%");
}
#[test]
fn bad_timestamps_say_why() {
let d = plus_ten();
let shape = |f: TimeFormat, s: &str| {
matches!(parse_time(&f, s.as_bytes(), &d), Err(TimeError::Shape(_)))
};
assert!(shape(TimeFormat::Iso8601, "2026-11-26T11:22:33 trailing"));
assert!(shape(TimeFormat::HttpDate, "26/Nov/2026:11:22:33 +11"));
assert!(shape(TimeFormat::Epoch(EpochUnit::Seconds), "12a"));
assert!(shape(TimeFormat::Epoch(EpochUnit::Seconds), ""));
assert!(matches!(
parse_time(&TimeFormat::Iso8601, b"2026-11-31T00:00:00Z", &d),
Err(TimeError::Range(_))
));
assert!(matches!(
parse_time(
&TimeFormat::Syslog,
b"Nov 6 08:01:02",
&TimeDefaults::default()
),
Err(TimeError::NoYear)
));
assert!(matches!(
parse_time(
&TimeFormat::Strptime("%b %d %H:%M:%S".into()),
b"May 27 02:45:27",
&TimeDefaults::default()
),
Err(TimeError::NoYear)
));
}
#[cfg(feature = "time-tz")]
#[test]
fn a_named_zone_follows_its_daylight_saving() {
let sydney = TimeDefaults {
zone: TimeZone::get("Australia/Sydney").unwrap(),
year: Some(2026),
now: None,
..TimeDefaults::default()
};
let at = |format: &TimeFormat, text: &str| {
parse_time(format, text.as_bytes(), &sydney)
.unwrap()
.to_string()
};
assert_eq!(
at(&TimeFormat::Iso8601, "2026-01-15 10:00:00"),
"2026-01-14T23:00:00Z"
);
assert_eq!(
at(&TimeFormat::Iso8601, "2026-07-15 10:00:00"),
"2026-07-15T00:00:00Z"
);
assert_eq!(
at(&TimeFormat::Syslog, "Jul 15 10:00:00"),
"2026-07-15T00:00:00Z"
);
assert_eq!(
at(&TimeFormat::Iso8601, "2026-01-15T10:00:00Z"),
"2026-01-15T10:00:00Z"
);
let utc = TimeFormat::Strptime("%Y-%m-%d %H:%M %Q".into());
assert_eq!(
parse_time(
&utc,
b"2026-01-15 10:00 Asia/Tokyo",
&TimeDefaults::default()
)
.unwrap()
.to_string(),
"2026-01-15T01:00:00Z"
);
}
#[test]
fn a_timestamp_with_no_year_takes_the_nearest_year() {
let read_at = |now: &str| TimeDefaults {
zone: TimeZone::UTC,
year: None,
now: Some(utc(now)),
..TimeDefaults::default()
};
let rows = [
(
"Dec 31 23:59:58",
"2027-01-01T00:00:03Z",
"2026-12-31T23:59:58Z",
),
(
"Jan 1 00:00:02",
"2026-12-31T23:59:59Z",
"2027-01-01T00:00:02Z",
),
(
"Nov 27 13:55:36",
"2026-11-27T14:00:00Z",
"2026-11-27T13:55:36Z",
),
(
"Jun 15 12:00:00",
"2026-11-27T14:00:00Z",
"2026-06-15T12:00:00Z",
),
(
"Nov 30 10:00:00",
"2026-03-01T00:00:00Z",
"2025-11-30T10:00:00Z",
),
];
for (text, now, want) in rows {
let got = parse_time(&TimeFormat::Syslog, text.as_bytes(), &read_at(now)).unwrap();
assert_eq!(got, utc(want), "{text} read at {now}");
}
let got = parse_time(
&TimeFormat::Strptime("%b %d %H:%M:%S".into()),
b"Dec 31 23:59:58",
&read_at("2027-01-01T00:00:03Z"),
)
.unwrap();
assert_eq!(got, utc("2026-12-31T23:59:58Z"));
let both = TimeDefaults {
year: Some(2020),
..read_at("2027-01-01T00:00:03Z")
};
assert_eq!(
parse_time(&TimeFormat::Syslog, b"Dec 31 23:59:58", &both).unwrap(),
utc("2020-12-31T23:59:58Z")
);
assert!(matches!(
parse_time(
&TimeFormat::Syslog,
b"Dec 31 23:59:58",
&TimeDefaults::default()
),
Err(TimeError::NoYear)
));
}
fn at_hours(hours: i8, year: i16) -> TimeDefaults {
TimeDefaults {
zone: TimeZone::fixed(Offset::from_hours(hours).unwrap()),
year: Some(year),
now: None,
..TimeDefaults::default()
}
}
fn java(pattern: &str) -> TimeFormat {
TimeFormat::strptime(StrptimeDialect::Java, pattern).unwrap()
}
const FRACTIONS: &str =
"yyyy-MM-dd HH:mm:ss[.SSSSSSSSS][.SSSSSSSS][.SSSSSSS][.SSSSSS][.SSSSS][.SSSS][.SSS][.SS][.S]X";
const CISCO: &str = "[EEE ]MMM [ ]d[ yyyy] HH:mm:ss[.SSS][ z]";
const JAVA_ROWS: &[(&str, &str, i8, Option<&str>)] = &[
("yyyy-MM-dd", "2024-12-15", 0, Some("2024-12-15T00:00:00Z")),
("yyyy-MM-dd", "not a date", 0, None),
("yyyy-MM-dd", "2024-12-15 extra", 0, None),
("yyyy-MM-dd", "", 0, None),
("yyyy-MM-dd", "2024-13-01", 0, None),
("yyyy-MM-dd", "2024-11-31", 0, None),
(
"yyyy-MM-dd HH:mm:ss",
"2024-12-15 09:30:00",
0,
Some("2024-12-15T09:30:00Z"),
),
(
"HH:mm:ss.SSS",
"18:32:29.495",
0,
Some("2026-01-01T18:32:29.495Z"),
),
("HH:mm:ss", "09:30:00", 0, Some("2026-01-01T09:30:00Z")),
("HH:mm:ss", "09:30:00", 11, Some("2025-12-31T22:30:00Z")),
("HH:mm:ss", "not a time", 0, None),
(
"yyyy-MM-dd'T'hh:mm:ssXXX",
"2022-05-30T04:12:12-07:00",
0,
Some("2022-05-30T07:00:00Z"),
),
(
"yyyy-MM-dd'T'hh:mm:ssXXX",
"2022-07-19T07:18:04-07:00",
0,
Some("2022-07-19T07:00:00Z"),
),
(
"yyyy-MM-dd'T'hh:mm:ss aXXX",
"2022-05-30T04:12:12 PM-07:00",
0,
Some("2022-05-30T23:12:12Z"),
),
(
"MMM d HH:mm:ss",
"Jun 11 09:30:00",
0,
Some("2026-06-11T09:30:00Z"),
),
(
"MMM dd yyyy HH:mm:ss",
"Nov 30 2026 10:00:01",
0,
Some("2026-11-30T10:00:01Z"),
),
(
FRACTIONS,
"2016-02-29 10:42:23-0700",
0,
Some("2016-02-29T17:42:23Z"),
),
(
FRACTIONS,
"2016-02-29 10:42:23.125-0700",
0,
Some("2016-02-29T17:42:23.125Z"),
),
(
"yyyy-MM-dd' 'HH:mm:ss' 'v",
"2022-11-18 10:10:57 +00:00",
0,
Some("2022-11-18T10:10:57Z"),
),
(
"YYYY-dd-MM HH:mm:ss",
"2020-01-16 08:00:31",
0,
Some("2019-12-29T08:00:31Z"),
),
("YYYY-dd-MM HH:mm:ss", "2020-1-16 08:00:31", 0, None),
(
"yyyy-MM-dd:HH:mm.SSSz",
"2019-01-01:01:01.000Z",
0,
Some("2019-01-01T00:00:00Z"),
),
(
"yyyy-MM-dd:HH:mm:ss.SSSz",
"2019-01-01:01:01:02.000Z",
0,
Some("2019-01-01T01:01:02Z"),
),
(CISCO, "May 5 17:51:17", 0, Some("2026-05-05T17:51:17Z")),
(
CISCO,
"Oct 10 2018 12:34:56",
0,
Some("2018-10-10T12:34:56Z"),
),
(
CISCO,
"Wed Oct 10 2018 12:34:56.5 AEST",
0,
Some("2018-10-10T02:34:56.5Z"),
),
(
"yyyy-MM-dd'T'HH:mm:ss.SSSX",
"2024-04-03T21:02:19.168Z",
0,
Some("2024-04-03T21:02:19.168Z"),
),
(
"yyyy-MM-dd'T'HH:mm:ssX",
"2024-04-03T21:02:19Z",
0,
Some("2024-04-03T21:02:19Z"),
),
(
"yyyy-MM-dd'T'HH:mm:ssXXX",
"2024-04-03T21:02:19Z",
0,
Some("2024-04-03T21:02:19Z"),
),
(
"yyyy-MM-dd'T'HH:mm:ssXXX",
"2024-04-03T21:02:19+05:30",
0,
Some("2024-04-03T15:32:19Z"),
),
("yyyy-MM-dd'T'HH:mm:ss", "2024-04-03T21:02:19Z", 0, None),
("yyyy-MM-dd'T'HH:mm:ssxxx", "2024-04-03T21:02:19Z", 0, None),
(
"yyyy-MM-dd'T'HH:mm:ssXXX",
"2024-04-03T21:02:19+25:00",
0,
None,
),
(
"yyyy MMM d HH:mm:ss zzz",
"2023 May 2 12:55:19 UTC",
0,
Some("2023-05-02T12:55:19Z"),
),
(
"yyyy MMM d HH:mm:ss",
"2023 Apr 7 09:36:56",
0,
Some("2023-04-07T09:36:56Z"),
),
(
"yyyy MMM d HH:mm:ss",
"2023 May 2 12:55:19",
10,
Some("2023-05-02T02:55:19Z"),
),
("yyyy MMM d HH:mm:ss", "not a date", 0, None),
(
"yyyy-MM-dd HH:mm:ss Z",
"2023-05-02 12:55:19 -0500",
10,
Some("2023-05-02T17:55:19Z"),
),
(
"yyyy-MM-dd HH:mm:ss z",
"2023-06-20 18:06:08\u{a0}AEST",
0,
Some("2023-06-20T08:06:08Z"),
),
(
"yyyy-MM-dd HH:mm:ss z",
"2023-06-20 18:06:08 \u{e9}AEST",
0,
None,
),
("yyyy-MM-dd HH:mm:ss z", "2023-06-20 18:06:08 XYZ", 0, None),
(
"yyyy-MM-dd HH:mm:ss z",
"2013-07-01 11:27:23 PST",
0,
Some("2013-07-01T19:27:23Z"),
),
(
"'abcdefghi\u{3a9}'yyyy-MM-dd HH:mm:ss",
"abcdefghi\u{3a9}2024-12-15 09:30:00",
10,
Some("2024-12-14T23:30:00Z"),
),
(
"yyyy-MM-dd'%H'HH:mm:ss",
"2024-12-15%H09:30:00",
0,
Some("2024-12-15T09:30:00Z"),
),
(
"yyyy-MM-dd HH:mm:ss.n Z z",
"2025-03-19 05:33:45.9196243 +0000 UTC",
0,
Some("2025-03-19T05:33:45.009196243Z"),
),
("yyyy-MM-dd HH:mm:ss.n", "2025-03-19 05:33:45.", 0, None),
(
"yyyy-MM-dd HH:mm:ss",
"2023-06-20 18:06:08",
-5,
Some("2023-06-20T23:06:08Z"),
),
("yyyyMMdd", "20250116", 0, Some("2025-01-16T00:00:00Z")),
(
"dd/MMM/yyyy:HH:mm:ss Z",
"26/Nov/2026:11:22:33 +1100",
0,
Some("2026-11-26T00:22:33Z"),
),
(
"EEE, d MMM yyyy HH:mm:ss Z",
"Tue, 30 Nov 2026 10:00:01 +0000",
0,
Some("2026-11-30T10:00:01Z"),
),
(
"EEEE, MMMM d, yyyy",
"Monday, November 30, 2026",
0,
Some("2026-11-30T00:00:00Z"),
),
(
"yyyy-MM-dd HH 'o''clock'",
"2026-11-30 10 o'clock",
0,
Some("2026-11-30T10:00:00Z"),
),
(
"yyyy-MM-dd''HH",
"2026-11-30'10",
0,
Some("2026-11-30T10:00:00Z"),
),
(
"yyyy-MM-dd G",
"2026-11-30 AD",
0,
Some("2026-11-30T00:00:00Z"),
),
("yyyy DDD", "2026 060", 0, Some("2026-03-01T00:00:00Z")),
(
"yyyy-MM-dd HH:mm VV",
"2026-01-15 10:00 +09:00",
0,
Some("2026-01-15T01:00:00Z"),
),
(
"yyyy-MM-dd HH:mm VV",
"2026-01-15 10:00 UTC",
5,
Some("2026-01-15T10:00:00Z"),
),
(
"yyyy-MM-dd HH:mm ZZZZ",
"2026-01-15 10:00 GMT+08:00",
0,
Some("2026-01-15T02:00:00Z"),
),
(
"yyyy-MM-dd HH:mm ZZZZZ",
"2026-01-15 10:00 Z",
3,
Some("2026-01-15T10:00:00Z"),
),
("yyyy-MM-dd HH:mm Z", "2026-01-15 10:00 Z", 3, None),
(
"yyyy-MM-dd[[ HH]:mm]",
"2026-01-15 10:30",
0,
Some("2026-01-15T10:30:00Z"),
),
(
"yyyy-MM-dd[[ HH]:mm]",
"2026-01-15",
0,
Some("2026-01-15T00:00:00Z"),
),
(
"yyyy-MM-dd[ HH",
"2026-01-15 10",
0,
Some("2026-01-15T10:00:00Z"),
),
(
"yyyy-MM-dd hh:mm[ a]",
"2026-11-30 04:12 PM",
0,
Some("2026-11-30T16:12:00Z"),
),
(
"yyyy-MM-dd hh:mm[ a]",
"2026-11-30 04:12",
0,
Some("2026-11-30T00:00:00Z"),
),
("yyyy-MM-dd hh:mm[ a]", "2026-11-30 13:12 PM", 0, None),
("[a ]hh:mm", "PM 04:12", 0, Some("2026-01-01T16:12:00Z")),
("[a ]hh:mm", "04:12", 0, Some("2026-01-01T00:00:00Z")),
(
"[YYYY-]MM-dd HH:mm",
"2020-01-16 08:00",
0,
Some("2019-12-29T08:00:00Z"),
),
(
"[YYYY-]MM-dd HH:mm",
"01-16 08:00",
0,
Some("2026-01-16T08:00:00Z"),
),
(
"MM-dd[ YYYY] HH:mm",
"01-16 2020 08:00",
0,
Some("2019-12-29T08:00:00Z"),
),
(
"MM-dd[ YYYY] HH:mm",
"01-16 08:00",
0,
Some("2026-01-16T08:00:00Z"),
),
];
#[test]
fn java_patterns_read_to_the_right_instant() {
let failed: Vec<String> = JAVA_ROWS
.iter()
.filter_map(|&(pattern, input, hours, want)| {
let got = parse_time(&java(pattern), input.as_bytes(), &at_hours(hours, 2026));
(got.as_ref().ok() != want.map(utc).as_ref())
.then(|| format!("{pattern:?} {input:?}: {got:?}, want {want:?}"))
})
.collect();
assert!(failed.is_empty(), "{failed:#?}");
}
#[test]
fn java_rows_read_as_trying_every_reading_does() {
for &(pattern, input, hours, _) in JAVA_ROWS {
let d = at_hours(hours, 2026);
let readings = java::oracle::build(pattern).unwrap();
let want = java::oracle::parse(&readings, input.as_bytes(), &d).ok();
let got = parse_stamp(&java(pattern), input.as_bytes(), &d).ok();
assert_eq!(got, want, "{pattern:?} {input:?}");
}
}
#[test]
fn a_format_list_takes_the_first_that_reads() {
let offsets_or_names = [
java("yyyy-MM-dd HH:mm:ss.SSSSSSz"),
java("yyyy-MM-dd HH:mm:ssz"),
java("yyyy-MM-dd'T'HH:mm:ss.SSSSSSz"),
java("yyyy-MM-dd'T'HH:mm:ssz"),
];
let fractions = [
java("yyyy-MM-dd HH:mm:ss.SSS"),
java("yyyy-MM-dd HH:mm:ss.SS"),
java("yyyy-MM-dd HH:mm:ss.S"),
];
let years = [java("dd/MM/yyyy H:mm:ss"), java("dd/MM/yy H:mm:ss")];
let epochs = [
TimeFormat::Epoch(EpochUnit::Seconds),
TimeFormat::Epoch(EpochUnit::Millis),
];
let zone_names = [java("dd-MMM-yyyy HH:mm:ss"), java("M/d/yy, h:m:s a z")];
let nexus = [java("yyyy MMM d HH:mm:ss zzz"), java("yyyy MMM d HH:mm:ss")];
let loader = [
TimeFormat::Iso8601,
TimeFormat::Strptime("%Y-%m-%d %H:%M:%S%.f".into()),
TimeFormat::Strptime("%Y-%m-%d %H:%M:%S".into()),
];
let rows: &[(&[TimeFormat], &str, i8, Option<&str>)] = &[
(
&offsets_or_names,
"2023-06-20 18:06:08.725000+00:00",
0,
Some("2023-06-20T18:06:08.725Z"),
),
(
&offsets_or_names,
"2023-06-20 18:06:08+00:00",
0,
Some("2023-06-20T18:06:08Z"),
),
(
&offsets_or_names,
"2023-06-08T12:00:29.962000+05:30",
0,
Some("2023-06-08T06:30:29.962Z"),
),
(
&offsets_or_names,
"2023-06-20 18:06:08 AEST",
0,
Some("2023-06-20T08:06:08Z"),
),
(&offsets_or_names, "2023-06-20 18:06:08", 0, None),
(
&fractions,
"2023-05-21 09:58:40.25",
0,
Some("2023-05-21T09:58:40.25Z"),
),
(
&fractions,
"2023-05-21 09:58:40.477",
0,
Some("2023-05-21T09:58:40.477Z"),
),
(&years, "24/10/23 7:07:31", -7, Some("2023-10-24T14:07:31Z")),
(
&years,
"24/10/2023 7:07:31",
0,
Some("2023-10-24T07:07:31Z"),
),
(&years, "24/10/023 7:07:31", 0, None),
(&epochs, "1587230269", 0, Some("2020-04-18T17:17:49Z")),
(&epochs, "1736935526", 0, Some("2025-01-15T10:05:26Z")),
(
&epochs[1..],
"1736935526000",
0,
Some("2025-01-15T10:05:26Z"),
),
(
&epochs,
"1742799479.852",
0,
Some("2025-03-24T06:57:59.852Z"),
),
(
&epochs,
"1742541951.883",
0,
Some("2025-03-21T07:25:51.883Z"),
),
(
&epochs,
"1636625755.218",
0,
Some("2021-11-11T10:15:55.218Z"),
),
(
&epochs,
"1742799480.061",
0,
Some("2025-03-24T06:58:00.061Z"),
),
(&epochs, "0", 0, Some("1970-01-01T00:00:00Z")),
(&epochs, "-86400", 0, Some("1969-12-31T00:00:00Z")),
(&epochs, "12a", 0, None),
(
&zone_names,
"2/20/25, 4:27:59 PM UTC+01:00",
0,
Some("2025-02-20T15:27:59Z"),
),
(
&nexus,
"2023 May 2 12:55:19 UTC",
0,
Some("2023-05-02T12:55:19Z"),
),
(
&nexus,
"2023 May 2 12:55:19",
0,
Some("2023-05-02T12:55:19Z"),
),
(
&loader,
"2024-01-15T10:30:00.123Z",
0,
Some("2024-01-15T10:30:00.123Z"),
),
(
&loader,
"2024-01-15 10:30:00.123",
0,
Some("2024-01-15T10:30:00.123Z"),
),
(&loader, "15/01/2024", 0, None),
(&[], "2024-01-15", 0, None),
];
let failed: Vec<String> = rows
.iter()
.filter_map(|&(formats, input, hours, want)| {
let got = parse_time_any(formats, input.as_bytes(), &at_hours(hours, 2026));
(got.as_ref().ok() != want.map(utc).as_ref())
.then(|| format!("{formats:?} {input:?}: {got:?}, want {want:?}"))
})
.collect();
assert!(failed.is_empty(), "{failed:#?}");
assert!(matches!(
parse_time_any(&[], b"0", &TimeDefaults::default()),
Err(TimeError::Shape(_))
));
}
#[test]
fn a_java_pattern_that_cant_be_read_fails_at_build() {
let eleven = "yyyy".to_owned() + &"[d]".repeat(11);
let rows: &[(&str, &str)] = &[
("ISO_INSTANT", "letter I"),
("yyyy-MM-dd QQ", "letter QQ"),
("yyyy-MM-dd K:mm", "letter K"),
("yyyy-MM-dd ddd", "letter ddd"),
("YYYY-MM-dd yyyy", "letter Y beside y or u"),
("YYYY-MM-dd E", "letter E beside Y"),
("yyyy 'T", "an unclosed quote"),
("yyyy]", "a ] with no ["),
(&eleven, "more than 1024 optional readings"),
("[YYYY ]ww", "letter ww"),
("[YYYY-]MM-dd MMMMM", "letter MMMMM"),
];
for &(pattern, want) in rows {
match TimeFormat::strptime(StrptimeDialect::Java, pattern) {
Err(TimeError::Pattern { pattern: p, part }) => {
assert_eq!((p.as_str(), part.as_str()), (pattern, want));
}
other => panic!("{pattern}: {other:?}"),
}
}
let nine = "yyyy-MM-dd HH:mm:ss[.SSSSSSSSS][.SSSSSSSS][.SSSSSSS][.SSSSSS][.SSSSS][.SSSS][.SSS][.SS][.S]X";
let TimeFormat::Java(built) = java(nine) else {
panic!("not a Java pattern");
};
assert_eq!((built.pattern(), built.readings_len()), (nine, 10));
}
#[test]
fn a_java_miss_says_why() {
let rows: &[(&str, &str, &str)] = &[
("yyyy-MM-dd", "not a date", "Shape"),
("yyyy-MM-dd", "2024-12-15 extra", "Shape"),
("[EEE ]MMM d HH:mm", "Nov 30 10-00", "Shape"),
("yyyy-MM-dd", "2024-13-01", "Range"),
("yyyy-MM-dd HH:mm", "2024-12-15 24:00", "Range"),
("yyyy-MM-dd", "2024-11-31", "Range"),
("MMM d HH:mm:ss", "May 27 02:45:27", "NoYear"),
];
for &(pattern, input, want) in rows {
let got = parse_time(&java(pattern), input.as_bytes(), &TimeDefaults::default());
let kind = match got {
Err(TimeError::Shape(_)) => "Shape",
Err(TimeError::Range(_)) => "Range",
Err(TimeError::NoYear) => "NoYear",
_ => "other",
};
assert_eq!(kind, want, "{pattern} {input}: {got:?}");
}
}
#[cfg(feature = "time-tz")]
#[test]
fn a_java_zone_name_follows_its_zone() {
let in_zone = |name: &str| TimeDefaults {
zone: TimeZone::get(name).unwrap(),
year: Some(2026),
now: None,
..TimeDefaults::default()
};
let rows: &[(&str, &str, &str, &str)] = &[
(
"yyyy-MM-dd",
"2024-12-15",
"Australia/Sydney",
"2024-12-14T13:00:00Z",
),
(
"HH:mm:ss",
"09:30:00",
"Australia/Sydney",
"2025-12-31T22:30:00Z",
),
(
"yyyy-MM-dd HH:mm:ss",
"2023-06-15 12:00:00",
"Europe/Paris",
"2023-06-15T10:00:00Z",
),
(
"yyyy-MM-dd HH:mm:ss.SSS",
"2023-05-22 16:32:28.771",
"America/Denver",
"2023-05-22T22:32:28.771Z",
),
(
"yyyy-MM-dd HH:mm:ss.SSS",
"2023-07-04 12:00:00.000",
"America/Denver",
"2023-07-04T18:00:00Z",
),
(
"yyyy-MM-dd HH:mm:ss.SSS",
"2023-01-04 12:00:00.000",
"America/Denver",
"2023-01-04T19:00:00Z",
),
(
"EEE., MMM d, HH:mm:ss z yyyy",
"Sat., Jan 5, 11:27:23 CST 2013",
"UTC",
"2013-01-05T17:27:23Z",
),
(
"EEE., MMM d, HH:mm:ss z yyyy",
"Mon., Jul 1, 11:27:23 CST 2013",
"UTC",
"2013-07-01T16:27:23Z",
),
(
"yyyy-MM-dd HH:mm VV",
"2026-01-15 10:00 Asia/Tokyo",
"UTC",
"2026-01-15T01:00:00Z",
),
(
"yyyy-MM-dd HH:mm z",
"2026-01-15 10:00 America/Port-au-Prince",
"UTC",
"2026-01-15T15:00:00Z",
),
];
for &(pattern, input, zone, want) in rows {
let got = parse_time(&java(pattern), input.as_bytes(), &in_zone(zone)).unwrap();
assert_eq!(got, utc(want), "{pattern} {input} in {zone}");
}
let years = [java("dd/MM/yyyy H:mm:ss"), java("dd/MM/yy H:mm:ss")];
let got = parse_time_any(&years, b"24/10/23 7:07:31", &in_zone("America/Los_Angeles"));
assert_eq!(got.unwrap(), utc("2023-10-24T14:07:31Z"));
let named = java("EEE., MMM d, HH:mm:ss z yyyy");
for (input, text) in [
(
"Sat., Jan 5, 11:27:23 CST 2013",
"2013-01-05T11:27:23-06:00",
),
(
"Mon., Jul 1, 11:27:23 CST 2013",
"2013-07-01T11:27:23-05:00",
),
] {
let got = parse_stamp(&named, input.as_bytes(), &in_zone("UTC")).unwrap();
let written = RenderFormat::Rfc3339(Fraction::Digits(0));
let zone = got.zone_or(&TimeZone::UTC);
assert_eq!(
render(got.timestamp, &written, &zone).unwrap(),
text,
"{input}"
);
}
}
#[test]
fn tai64n_reads_to_the_right_instant() {
let rows: &[(&str, Option<&str>)] = &[
("@40000000692b890a1dcd6500", Some("2025-11-30T00:00:00.5Z")),
("40000000692b890a1dcd6500", Some("2025-11-30T00:00:00.5Z")),
("@40000000692B890A1DCD6500", Some("2025-11-30T00:00:00.5Z")),
("@400000000000000a00000000", Some("1970-01-01T00:00:00Z")),
(
"@40000000000000093b9ac9ff",
Some("1969-12-31T23:59:59.999999999Z"),
),
("@40000000692b890a3b9aca00", None),
("@40000000692b890a1dcd650", None),
("@40000000692b890a1dcd65000", None),
("@40000000692b890g1dcd6500", None),
("@", None),
("", None),
];
for &(input, want) in rows {
let got = parse_time(
&TimeFormat::Tai64n,
input.as_bytes(),
&TimeDefaults::default(),
);
assert_eq!(
got.as_ref().ok(),
want.map(utc).as_ref(),
"{input}: {got:?}"
);
}
}
#[test]
fn an_epoch_picks_its_unit_by_size() {
let rows: &[(&str, Option<&str>)] = &[
("0", Some("1970-01-01T00:00:00Z")),
("1764460800", Some("2025-11-30T00:00:00Z")),
("253402207200", Some("9999-12-30T22:00:00Z")),
("253402207201", None),
("1000000000000", None),
("1000000000001", Some("2001-09-09T01:46:40.001Z")),
("1764460800000", Some("2025-11-30T00:00:00Z")),
("1000000000000000", None),
("1000000000000001", Some("2001-09-09T01:46:40.000001Z")),
("1764460800123456", Some("2025-11-30T00:00:00.123456Z")),
("1764460800000000", Some("2025-11-30T00:00:00Z")),
("1000000000000000000", None),
(
"1000000000000000001",
Some("2001-09-09T01:46:40.000000001Z"),
),
(
"1764460800123456789",
Some("2025-11-30T00:00:00.123456789Z"),
),
("-86400", Some("1969-12-31T00:00:00Z")),
("-1000000000001", Some("1938-04-24T22:13:19.999Z")),
("-1.5", Some("1969-12-31T23:59:58.5Z")),
("1764460800.5", Some("2025-11-30T00:00:00.5Z")),
("1764460800000.25", Some("2025-11-30T00:00:00.00025Z")),
("1764460800123456.7", Some("2025-11-30T00:00:00.1234567Z")),
(
"1764460800123456789.9",
Some("2025-11-30T00:00:00.123456789Z"),
),
("1.2.3", None),
("-", None),
("", None),
];
let auto = TimeFormat::Epoch(EpochUnit::Auto);
for &(input, want) in rows {
let got = parse_time(&auto, input.as_bytes(), &TimeDefaults::default());
assert_eq!(
got.as_ref().ok(),
want.map(utc).as_ref(),
"{input}: {got:?}"
);
}
}
const WINDOWS_COUNTS: &[(&str, &str, &str)] = &[
(
"134406505845670000",
"639317737845670000",
"2026-12-02T02:03:04.5670000Z",
),
(
"134060905845670000",
"638972137845670000",
"2025-10-28T02:03:04.5670000Z",
),
("1", "504911232000000001", "1601-01-01T00:00:00.0000001Z"),
];
fn read(format: &TimeFormat, text: &str) -> Result<Timestamp, TimeError> {
parse_time(format, text.as_bytes(), &TimeDefaults::default())
}
#[test]
fn windows_tick_counts_read_to_the_instant_dotnet_wrote() {
let filetime = TimeFormat::Epoch(EpochUnit::FileTime);
let ticks = TimeFormat::Epoch(EpochUnit::DotNetTicks);
for &(ft, dotnet, iso) in WINDOWS_COUNTS {
assert_eq!(read(&filetime, ft).unwrap(), utc(iso), "FILETIME {ft}");
assert_eq!(read(&ticks, dotnet).unwrap(), utc(iso), "ticks {dotnet}");
}
let defaults = TimeDefaults::default();
let stamp = parse_stamp(&filetime, b"134406505845670000", &defaults).unwrap();
assert_eq!(stamp.offset, Some(Offset::UTC));
let local = parse_stamp(&ticks, b"639317737845670000", &plus_ten()).unwrap();
assert_eq!(local.offset, None);
assert_eq!(local.timestamp, utc("2026-12-01T16:03:04.567Z"));
assert_eq!(
read(&filetime, "116444736000000000").unwrap(),
utc("1970-01-01T00:00:00Z")
);
assert_eq!(
read(&ticks, "621355968000000000").unwrap(),
utc("1970-01-01T00:00:00Z")
);
assert_eq!(
read(&filetime, "116444735999999999").unwrap(),
utc("1969-12-31T23:59:59.9999999Z")
);
}
#[test]
fn a_windows_tick_count_that_is_not_a_time_is_an_error() {
let rows: &[(&str, fn(&TimeError) -> bool)] = &[
("0", |e| matches!(e, TimeError::Never)),
("0000", |e| matches!(e, TimeError::Never)),
("9223372036854775807", |e| matches!(e, TimeError::Never)),
("-1", |e| matches!(e, TimeError::Shape(_))),
("1.5", |e| matches!(e, TimeError::Shape(_))),
("1.", |e| matches!(e, TimeError::Shape(_))),
("12a", |e| matches!(e, TimeError::Shape(_))),
(" 1", |e| matches!(e, TimeError::Shape(_))),
("", |e| matches!(e, TimeError::Shape(_))),
("18446744073709551616", |e| matches!(e, TimeError::Shape(_))),
("123456789012345678901", |e| {
matches!(e, TimeError::Shape(_))
}),
("18446744073709551615", |e| matches!(e, TimeError::Range(_))),
("9223372036854775806", |e| matches!(e, TimeError::Range(_))),
];
for unit in [EpochUnit::FileTime, EpochUnit::DotNetTicks] {
let format = TimeFormat::Epoch(unit);
for &(text, is_expected) in rows {
let got = read(&format, text);
assert!(
got.as_ref().is_err_and(is_expected),
"{unit:?} {text:?}: {got:?}"
);
}
}
assert!(read(&TimeFormat::Epoch(EpochUnit::DotNetTicks), "1").is_ok());
assert!(read(&TimeFormat::Epoch(EpochUnit::FileTime), "1").is_ok());
}
type Kind = fn(&Result<Timestamp, TimeError>) -> bool;
#[test]
fn auto_refuses_the_size_of_a_windows_count_and_never_picks_a_windows_unit() {
let auto = TimeFormat::Epoch(EpochUnit::Auto);
for &(ft, dotnet, _) in &WINDOWS_COUNTS[..2] {
for text in [ft, dotnet] {
let got = read(&auto, text);
assert!(matches!(got, Err(TimeError::UnitNeeded)), "{text}: {got:?}");
}
}
let micros = read(&TimeFormat::Epoch(EpochUnit::Micros), WINDOWS_COUNTS[0].0);
assert_eq!(micros.unwrap(), utc("6229-03-04T20:30:45.67Z"));
let ok: Kind = |r| r.is_ok();
let unit: Kind = |r| matches!(r, Err(TimeError::UnitNeeded));
let range: Kind = |r| matches!(r, Err(TimeError::Range(_)));
let rows: &[(&str, Kind)] = &[
("100000000000000000", unit),
("999999999999999999", unit),
("000134406505845670000", unit),
("99999999999999999", ok),
("1000000000000000000", range),
("1764460800123456789", ok),
("-134406505845670000", ok),
];
for &(text, expected) in rows {
let got = read(&auto, text);
assert!(expected(&got), "{text}: {got:?}");
}
}
#[test]
fn a_powershell_json_date_reads_with_or_without_its_backslashes() {
let json = TimeFormat::MsJsonDate;
let when = utc("2026-12-02T02:03:04.567Z");
for text in [
r"\/Date(1796176984567)\/",
"/Date(1796176984567)/",
r"\/Date(1796176984567)/",
r"/Date(1796176984567)\/",
] {
assert_eq!(read(&json, text).unwrap(), when, "{text}");
}
let defaults = TimeDefaults::default();
for (text, hours) in [
(r"\/Date(1796176984567+1000)\/", 10),
(r"\/Date(1796176984567-0700)\/", -7),
(r"\/Date(1796176984567+0000)\/", 0),
] {
let stamp = parse_stamp(&json, text.as_bytes(), &defaults).unwrap();
assert_eq!(stamp.timestamp, when, "{text}");
assert_eq!(
stamp.offset,
Some(Offset::from_hours(hours).unwrap()),
"{text}"
);
}
assert_eq!(
read(&json, "/Date(0)/").unwrap(),
utc("1970-01-01T00:00:00Z")
);
assert_eq!(
read(&json, r"\/Date(-62135596800000)\/").unwrap(),
utc("0001-01-01T00:00:00Z")
);
for text in [
"",
"Date(1)",
"/Date(1)",
"Date(1)/",
"/Date()/",
"/Date(-)/",
"/date(1)/",
"/Date(1.5)/",
"/Date(1e3)/",
"/Date(1)/ ",
" /Date(1)/",
"/Date(1+10)/",
"/Date(1+10000)/",
"/Date(1+2460)/",
"/Date(1+2400)/",
"/Date(1 +1000)/",
"/Date(1)+1000/",
"//Date(1)//",
"/Date(253402207201000)/",
"/Date(99999999999999999999)/",
"/Date(123456789012345678901)/",
] {
assert!(read(&json, text).is_err(), "{text:?}");
}
}
#[test]
fn the_lab_vms_windows_times_read_as_each_other_and_as_their_own_iso_text() {
use crate::shared_tests::windows_text::lab;
let filetime = TimeFormat::Epoch(EpochUnit::FileTime);
let ticks = TimeFormat::Epoch(EpochUnit::DotNetTicks);
for (image, bytes) in lab("win_time.csv") {
let text = String::from_utf8(bytes).unwrap();
let rows: Vec<Vec<&str>> = text
.lines()
.skip(1)
.map(|l| l.split(',').collect())
.collect();
assert!(!rows.is_empty(), "{image}");
for row in rows {
let &[ft, dotnet, iso] = row.as_slice() else {
panic!("{image}: {row:?}")
};
assert_eq!(read(&filetime, ft).unwrap(), utc(iso), "{image} {ft}");
assert_eq!(read(&ticks, dotnet).unwrap(), utc(iso), "{image} {dotnet}");
}
}
for (image, bytes) in lab("ps_date.json") {
let doc: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let when = doc["when"].as_str().unwrap();
let logon = doc["lastLogon"].as_i64().unwrap();
assert!(
when.starts_with("/Date("),
"the parsed string has no backslashes: {when}"
);
assert_eq!(
read(&TimeFormat::MsJsonDate, when).unwrap(),
read(&filetime, &logon.to_string()).unwrap(),
"{image}"
);
}
for (image, bytes) in lab("ps_process.json") {
let text = String::from_utf8(bytes).unwrap();
let dates: Vec<&str> = text
.split('"')
.filter(|s| s.starts_with(r"\/Date("))
.collect();
assert!(dates.len() >= 5, "{image}: {dates:?}");
for date in dates {
let ms: i64 = date[7..date.len() - 3].parse().unwrap();
let want = Timestamp::from_millisecond(ms).unwrap();
assert_eq!(
read(&TimeFormat::MsJsonDate, date).unwrap(),
want,
"{image} {date}"
);
}
}
}
proptest::proptest! {
#[test]
fn the_windows_readers_never_panic(
text in proptest::prop_oneof!["\\PC{0,40}", "/?Date\\([-+0-9]{0,24}\\)/?", "[0-9]{0,24}"],
) {
for format in [
TimeFormat::Epoch(EpochUnit::FileTime),
TimeFormat::Epoch(EpochUnit::DotNetTicks),
TimeFormat::MsJsonDate,
TimeFormat::Epoch(EpochUnit::Auto),
] {
let _ = read(&format, &text);
}
}
#[test]
fn an_instant_written_as_a_windows_count_reads_back(
secs in -11_644_473_599_i64..253_402_207_200,
hundred_ns in 0_i64..10_000_000,
) {
let unix_ticks = i128::from(secs) * 10_000_000 + i128::from(hundred_ns);
let instant = Timestamp::from_nanosecond(unix_ticks * 100).unwrap();
let filetime = (unix_ticks + 116_444_736_000_000_000).to_string();
proptest::prop_assert_eq!(read(&TimeFormat::Epoch(EpochUnit::FileTime), &filetime).unwrap(), instant);
let dotnet = (unix_ticks + 621_355_968_000_000_000).to_string();
proptest::prop_assert_eq!(read(&TimeFormat::Epoch(EpochUnit::DotNetTicks), &dotnet).unwrap(), instant);
let millis = i128::from(secs) * 1000 + i128::from(hundred_ns / 10_000);
let json = format!("/Date({millis})/");
let whole_ms = Timestamp::from_nanosecond(millis * 1_000_000).unwrap();
proptest::prop_assert_eq!(read(&TimeFormat::MsJsonDate, &json).unwrap(), whole_ms);
}
}
const ROUND_TRIPS: &[(&str, &str, u32)] = &[
(
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSXXX",
"%Y-%m-%dT%H:%M:%S.%9f%:z",
9,
),
("yyyy-MM-dd HH:mm:ss.SSS Z", "%Y-%m-%d %H:%M:%S.%3f %z", 3),
("dd/MMM/yyyy:HH:mm:ss Z", "%d/%b/%Y:%H:%M:%S %z", 0),
("EEE, d MMM yyyy HH:mm:ss X", "%a, %-d %b %Y %H:%M:%S %z", 0),
("MMM dd yyyy HH:mm:ss", "%b %d %Y %H:%M:%S", 0),
(
"EEEE, MMMM d, yyyy h:mm:ss a VV",
"%A, %B %-d, %Y %-I:%M:%S %p %:z",
0,
),
("yyyyMMddHHmmssSSS", "%Y%m%d%H%M%S%3f", 3),
(
"yyyy-MM-dd'T'HH:mm:ss[.SSSSSS]x",
"%Y-%m-%dT%H:%M:%S.%6f%z",
6,
),
("yyyy-MM-dd'T'HH:mm:ss[.SSSSSS]x", "%Y-%m-%dT%H:%M:%S%z", 0),
("yyyy DDD HH:mm:ss z", "%Y %j %H:%M:%S %:z", 0),
];
proptest::proptest! {
#[test]
fn a_java_pattern_reads_back_what_jiff_wrote(
secs in -30_610_224_000_i64..=253_402_214_399,
nanos in 0_i32..1_000_000_000,
quarter_hours in -48_i32..=56,
row in 0..ROUND_TRIPS.len(),
) {
let (pattern, written, digits) = ROUND_TRIPS[row];
let ns = i128::from(secs) * 1_000_000_000 + i128::from(nanos);
let ts = Timestamp::from_nanosecond(ns).unwrap();
let offset = Offset::from_seconds(quarter_hours * 900).unwrap();
let zoned = ts.to_zoned_datetime(TimeZone::fixed(offset));
let text = jiff::fmt::strtime::format(written, &zoned).unwrap();
let d = TimeDefaults { zone: TimeZone::fixed(offset), year: None, now: None, ..TimeDefaults::default() };
let step = 10_i128.pow(9 - digits);
let want = Timestamp::from_nanosecond(ns - ns.rem_euclid(step)).unwrap();
let got = parse_time(&java(pattern), text.as_bytes(), &d);
proptest::prop_assert_eq!(got.ok(), Some(want), "{} {}", pattern, text);
}
#[test]
fn iso8601_reads_all_the_grok_field_matches(
date in (1970_u16..2100, 1_u8..=12, 1_u8..=28, 0_u8..24, 0_u8..60),
tail in "(:?[0-9]{1,2}([:.,][0-9]{1,4})?)?",
sep in "[Tt ]",
zone in "([Zz]|[+-][0-2][0-9](:?[0-6][0-9])?)?",
) {
let (y, mo, d, h, mi) = date;
let text = format!("{y:04}-{mo:02}-{d:02}{sep}{h:02}:{mi:02}{tail}{zone}");
let grok = text.replacen('t', "T", 1).replace('z', "Z");
let scanned = matches!(
crate::field::field("TIMESTAMP_ISO8601").map(|f| (f.scan)(grok.as_bytes(), 0)),
Some(crate::field::Scan::Match(end)) if end == grok.len()
);
let got = parse_stamp(&TimeFormat::Iso8601, text.as_bytes(), &TimeDefaults::default());
let digits = zone.replace(':', "");
let part = |r: std::ops::Range<usize>| digits.get(r).map_or(0, |d| d.parse::<u8>().unwrap_or(0));
let (hh, mm) = (part(1..3), part(3..5));
let leap = tail.trim_start_matches(':').starts_with("60");
if scanned && hh <= 23 && mm <= 59 && !leap {
proptest::prop_assert!(got.is_ok(), "{} {:?}", text, got);
}
if let Ok(stamp) = got {
proptest::prop_assert_eq!(stamp.offset.is_some(), !zone.is_empty(), "{}", text);
}
}
}
/// `ThisYear` takes the year `now` is in, where `Nearest` would move a
/// December line read in January back a year.
#[test]
fn this_year_takes_the_year_now_is_in() {
let read_at = |now: &str, year_rule| TimeDefaults {
now: Some(utc(now)),
year_rule,
..TimeDefaults::default()
};
let rows: &[(TimeFormat, &str, &str, YearRule, &str)] = &[
(
TimeFormat::Syslog,
"Dec 31 23:59:58",
"2027-01-01T00:00:03Z",
YearRule::ThisYear,
"2027-12-31T23:59:58Z",
),
(
TimeFormat::Syslog,
"Dec 31 23:59:58",
"2027-01-01T00:00:03Z",
YearRule::Nearest,
"2026-12-31T23:59:58Z",
),
(
java("MMM d HH:mm:ss"),
"Jun 11 09:30:00",
"2026-11-30T00:00:00Z",
YearRule::ThisYear,
"2026-06-11T09:30:00Z",
),
(
java("HH:mm:ss.SSS"),
"18:32:29.495",
"2026-08-15T00:00:00Z",
YearRule::ThisYear,
"2026-01-01T18:32:29.495Z",
),
(
TimeFormat::Strptime("%b %d %H:%M:%S".into()),
"Nov 30 10:00:00",
"2026-03-01T00:00:00Z",
YearRule::ThisYear,
"2026-11-30T10:00:00Z",
),
];
for (format, text, now, rule, want) in rows {
let got = parse_time(format, text.as_bytes(), &read_at(now, *rule)).unwrap();
assert_eq!(
got,
utc(want),
"{format:?} {text} read at {now} by {rule:?}"
);
}
}
fn zone_at(secs: i32) -> TimeZone {
TimeZone::fixed(Offset::from_seconds(secs).unwrap())
}
/// A Java-style pattern to print with.
fn printer(pattern: &str) -> RenderFormat {
match java(pattern) {
TimeFormat::Java(built) => RenderFormat::Java(built),
other => panic!("{other:?}"),
}
}
/// Each output form of one instant in a zone, in seconds east.
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 30 cases")]
fn each_render_format_writes_the_instant() {
let rows: &[(RenderFormat, &str, i32, &str)] = &[
(
RenderFormat::Rfc3339(Fraction::Digits(3)),
"2024-12-14T13:00:00Z",
39_600,
"2024-12-15T00:00:00.000+11:00",
),
(
RenderFormat::Rfc3339(Fraction::Digits(3)),
"2021-05-26T16:26:47.123456789Z",
0,
"2021-05-26T16:26:47.123Z",
),
(
RenderFormat::Rfc3339(Fraction::Digits(0)),
"2021-05-26T16:26:47.123456789Z",
0,
"2021-05-26T16:26:47Z",
),
(
RenderFormat::Rfc3339(Fraction::Digits(12)),
"2021-05-26T16:26:47.1Z",
-19_800,
"2021-05-26T10:56:47.100000000-05:30",
),
(
RenderFormat::Rfc3339(Fraction::Trimmed(3)),
"2025-04-16T03:01:01.1951498Z",
0,
"2025-04-16T03:01:01.1951498Z",
),
(
RenderFormat::Rfc3339(Fraction::Trimmed(3)),
"2025-04-15T07:13:45.52835Z",
0,
"2025-04-15T07:13:45.52835Z",
),
(
RenderFormat::Rfc3339(Fraction::Trimmed(3)),
"2025-04-16T03:01:01Z",
0,
"2025-04-16T03:01:01.000Z",
),
(
RenderFormat::Rfc3339(Fraction::Trimmed(0)),
"2025-04-16T03:01:01Z",
0,
"2025-04-16T03:01:01Z",
),
(
RenderFormat::Rfc3339(Fraction::Groups(3)),
"2026-04-07T07:03:00.12Z",
0,
"2026-04-07T07:03:00.120Z",
),
(
RenderFormat::Rfc3339(Fraction::Groups(3)),
"2026-04-07T07:03:00.1234Z",
0,
"2026-04-07T07:03:00.123400Z",
),
(
RenderFormat::Rfc3339(Fraction::Groups(0)),
"2026-04-07T07:03:00Z",
0,
"2026-04-07T07:03:00Z",
),
(
RenderFormat::Rfc3339(Fraction::Groups(0)),
"2026-04-07T07:03:00.000000001Z",
0,
"2026-04-07T07:03:00.000000001Z",
),
(
RenderFormat::Rfc3339(Fraction::Digits(3)),
"-000001-01-01T00:00:00Z",
0,
"-0001-01-01T00:00:00.000Z",
),
(
RenderFormat::Rfc3339(Fraction::Digits(3)),
"2017-01-31T08:46:49Z",
19_800,
"2017-01-31T14:16:49.000+05:30",
),
(
RenderFormat::EpochMillis,
"2024-07-01T10:48:39.852Z",
36_000,
"1719830919852",
),
(
RenderFormat::EpochSeconds,
"2024-07-01T10:48:39Z",
0,
"1719830919",
),
(
RenderFormat::EpochSeconds,
"1969-12-31T23:59:59.500Z",
0,
"-0.5",
),
(
RenderFormat::EpochSeconds,
"1969-12-31T23:59:58.250Z",
0,
"-1.75",
),
(RenderFormat::EpochSeconds, "1969-12-31T23:59:59Z", 0, "-1"),
(
RenderFormat::EpochSeconds,
"1970-01-01T00:00:00.500Z",
0,
"0.5",
),
(RenderFormat::EpochSeconds, "1970-01-01T00:00:01Z", 0, "1"),
(
RenderFormat::EpochMillis,
"1969-12-31T23:59:59.9995Z",
0,
"-1",
),
(
RenderFormat::EpochMicros,
"2025-11-30T00:00:00.123456789Z",
0,
"1764460800123456",
),
(
RenderFormat::EpochNanos,
"2025-11-30T00:00:00.123456789Z",
0,
"1764460800123456789",
),
(RenderFormat::EpochNanos, "1970-01-01T00:00:00Z", 0, "0"),
(RenderFormat::Date, "2025-01-16T04:05:06Z", 0, "2025-01-16"),
(
RenderFormat::Date,
"2025-01-16T20:05:06Z",
36_000,
"2025-01-17",
),
(
RenderFormat::Strftime("%Y-%m-%d %H:%M:%S%.f %:z".into()),
"2026-11-30T00:00:01.5Z",
36_000,
"2026-11-30 10:00:01.5 +10:00",
),
(
RenderFormat::Strftime("%b %d %Y %H:%M:%S.%3f".into()),
"2026-11-30T00:00:01.5Z",
0,
"Nov 30 2026 00:00:01.500",
),
(
printer("yyyy-MM-dd HH:mm:ss"),
"2024-07-01T10:48:39.852Z",
0,
"2024-07-01 10:48:39",
),
];
let failed: Vec<String> = rows
.iter()
.filter_map(|(format, at, secs, want)| {
let got = render(utc(at), format, &zone_at(*secs));
(got.as_deref().ok() != Some(*want))
.then(|| format!("{format:?} {at} at {secs}: {got:?}, want {want}"))
})
.collect();
assert!(failed.is_empty(), "{failed:#?}");
let mut out = String::from("at ");
let day = utc("2026-11-30T00:00:00Z");
render_into(day, &RenderFormat::Date, &TimeZone::UTC, &mut out).unwrap();
assert_eq!(out, "at 2026-11-30");
}
/// Java-style patterns printed as Java prints each letter at each width,
/// the instant in UTC and the zone in seconds east.
const JAVA_PRINTS: &[(&str, &str, i32, &str)] = &[
(
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"2026-11-30T00:00:01.123Z",
39_600,
"2026-11-30T11:00:01.123+11:00",
),
(
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"2026-11-30T00:00:01.123Z",
0,
"2026-11-30T00:00:01.123Z",
),
(
"yyyy-MM-dd'T'HH:mm:ss.SSSxxx",
"2026-11-30T00:00:01.123Z",
0,
"2026-11-30T00:00:01.123+00:00",
),
(
"dd/MMM/yyyy:HH:mm:ss Z",
"2026-11-30T00:00:01Z",
39_600,
"30/Nov/2026:11:00:01 +1100",
),
(
"dd/MMM/yyyy:HH:mm:ss Z",
"2026-11-30T00:00:01Z",
0,
"30/Nov/2026:00:00:01 +0000",
),
(
"EEE, d MMM yyyy HH:mm:ss X",
"2026-11-30T04:30:01Z",
19_800,
"Mon, 30 Nov 2026 10:00:01 +0530",
),
(
"X XX XXX",
"2026-11-30T00:00:00Z",
36_000,
"+10 +1000 +10:00",
),
("XXXX XXXXX", "2026-11-30T00:00:00Z", -9_000, "-0230 -02:30"),
(
"XXXX XXXXX",
"2026-11-30T00:00:00Z",
36_005,
"+100005 +10:00:05",
),
("x xx xxx", "2026-11-30T00:00:00Z", 0, "+00 +0000 +00:00"),
("X Z ZZZZZ", "2026-11-30T00:00:00Z", 0, "Z +0000 Z"),
("ZZZZ", "2026-11-30T00:00:00Z", 36_000, "GMT+10:00"),
("ZZZZ", "2026-11-30T00:00:00Z", 0, "GMT"),
("ZZZZZ", "2026-11-30T00:00:00Z", 36_000, "+10:00"),
(
"EEEE, MMMM d, yyyy h:mm:ss a",
"2026-11-30T22:05:00Z",
0,
"Monday, November 30, 2026 10:05:00 PM",
),
("hh:mm a", "2026-11-30T00:05:00Z", 0, "12:05 AM"),
("hh:mm a", "2026-11-30T12:05:00Z", 0, "12:05 PM"),
("k:mm H:mm HH", "2026-11-30T00:30:00Z", 0, "24:30 0:30 00"),
(
"y yy yyyy u-M-d",
"2026-11-30T00:00:00Z",
0,
"2026 26 2026 2026-11-30",
),
(
"y yyy yyyy-MM-dd",
"0023-05-01T00:00:00Z",
0,
"23 023 0023-05-01",
),
("D DD DDD", "2026-03-01T00:00:00Z", 0, "60 60 060"),
("D DDD", "2026-01-05T00:00:00Z", 0, "5 005"),
// The week-based year starts on the Sunday on or before 1 January.
("YYYY", "2019-12-29T00:00:00Z", 0, "2020"),
("YYYY", "2019-12-28T00:00:00Z", 0, "2019"),
("YYYY-ww", "2020-01-04T00:00:00Z", 0, "2020-01"),
("YYYY-ww", "2020-01-05T00:00:00Z", 0, "2020-02"),
("YY-w W F", "2026-11-30T00:00:00Z", 0, "26-49 5 5"),
(
"YYYY-dd-MM HH:mm:ss",
"2019-12-29T08:00:31Z",
0,
"2020-29-12 08:00:31",
),
("ss.n", "2025-03-19T05:33:45.009196243Z", 0, "45.9196243"),
("N", "2026-11-30T00:00:01.000000005Z", 0, "1000000005"),
(
"S SSS SSSSSS",
"2026-11-30T10:00:01.123456789Z",
0,
"1 123 123456",
),
("G yyyy", "2026-11-30T10:00:00Z", 0, "AD 2026"),
(
"yyyy-MM-dd'T'HH 'o''clock' ''",
"2026-11-30T10:00:00Z",
0,
"2026-11-30T10 o'clock '",
),
(
"[EEE ]MMM d[ yyyy] HH:mm:ss[.SSS][ z]",
"2026-11-30T10:00:00Z",
36_000,
"Mon Nov 30 2026 20:00:00.000 +10:00",
),
("VV", "2026-11-30T10:00:00Z", 36_000, "+10:00"),
("hh", "2026-11-30T22:00:00Z", 0, "10"),
];
#[test]
fn java_patterns_print_as_java_does() {
let failed: Vec<String> = JAVA_PRINTS
.iter()
.filter_map(|&(pattern, at, secs, want)| {
let got = render(utc(at), &printer(pattern), &zone_at(secs));
(got.as_deref().ok() != Some(want))
.then(|| format!("{pattern:?} {at} at {secs}: {got:?}, want {want:?}"))
})
.collect();
assert!(failed.is_empty(), "{failed:#?}");
let at = utc("2026-11-30T10:00:00Z");
assert_eq!(
render(at, &printer("z VV"), &TimeZone::UTC).unwrap(),
"UTC UTC"
);
}
proptest::proptest! {
/// A pattern reads back what it printed, cut to the digits of a second
/// it keeps, at any instant and offset.
#[test]
fn a_java_pattern_reads_back_what_it_printed(
secs in -30_610_224_000_i64..=253_402_214_399,
nanos in 0_i32..1_000_000_000,
quarter_hours in -48_i32..=56,
row in 0..ROUND_TRIPS.len(),
) {
let pattern = ROUND_TRIPS[row].0;
// Every section prints, so the fraction kept is the pattern's longest.
let digits = u32::try_from(pattern.split(|c| c != 'S').map(str::len).max().unwrap_or(0)).unwrap();
let ns = i128::from(secs) * 1_000_000_000 + i128::from(nanos);
let ts = Timestamp::from_nanosecond(ns).unwrap();
let zone = zone_at(quarter_hours * 900);
let text = render(ts, &printer(pattern), &zone).unwrap();
let d = TimeDefaults { zone, ..TimeDefaults::default() };
let step = 10_i128.pow(9 - digits);
let want = Timestamp::from_nanosecond(ns - ns.rem_euclid(step)).unwrap();
let got = parse_time(&java(pattern), text.as_bytes(), &d);
proptest::prop_assert_eq!(got.ok(), Some(want), "{} {}", pattern, text);
}
}
#[cfg(feature = "time-tz")]
#[test]
fn a_java_zone_letter_prints_the_named_zone() {
let sydney = TimeZone::get("Australia/Sydney").unwrap();
let at = |pattern: &str, ts: &str| render(utc(ts), &printer(pattern), &sydney).unwrap();
assert_eq!(
at("HH:mm z VV XXX", "2026-11-30T00:00:00Z"),
"11:00 AEDT Australia/Sydney +11:00"
);
assert_eq!(
at("HH:mm z XXX", "2026-07-01T00:00:00Z"),
"10:00 AEST +10:00"
);
let millis = RenderFormat::Rfc3339(Fraction::Digits(3));
assert_eq!(
render(utc("2024-12-14T13:00:00Z"), &millis, &sydney).unwrap(),
"2024-12-15T00:00:00.000+11:00"
);
}
/// The consumer's date step built from grippo's parts: the first format that
/// reads, the configured zone for a text with none, and RFC 3339 with
/// milliseconds in that zone, else in UTC or by the output format.
fn consumer_date(
input: &str,
formats: &[TimeFormat],
zone: Option<&TimeZone>,
output: Option<&RenderFormat>,
) -> Option<String> {
let d = TimeDefaults {
zone: zone.cloned().unwrap_or(TimeZone::UTC),
now: Some(utc("2026-08-15T00:00:00Z")),
year_rule: YearRule::ThisYear,
..TimeDefaults::default()
};
let stamp = parse_stamp_any(formats, input.trim().as_bytes(), &d).ok()?;
let millis = RenderFormat::Rfc3339(Fraction::Digits(3));
let (format, out_zone) = match (output, zone) {
(Some(format), _) => (format, TimeZone::UTC),
(None, Some(zone)) if stamp.offset.is_none() => (&millis, zone.clone()),
(None, _) => (&millis, TimeZone::UTC),
};
render(stamp.timestamp, format, &out_zone).ok()
}
type ConsumerRow = (
&'static str,
Vec<TimeFormat>,
Option<i32>,
Option<RenderFormat>,
Option<&'static str>,
);
/// The consumer's date tests, each row its input, formats, configured zone
/// in seconds east, output format and expected text. A year the text lacks
/// is the year it is read in, 2026.
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 35 cases")]
fn the_consumer_date_tests_read_and_write_the_same() {
let iso = || vec![TimeFormat::Iso8601, java("yyyy-MM-dd")];
let seconds = TimeFormat::Epoch(EpochUnit::Seconds);
let millis = TimeFormat::Epoch(EpochUnit::Millis);
let fractions = || {
vec![
java("yyyy-MM-dd HH:mm:ss.SSS"),
java("yyyy-MM-dd HH:mm:ss.SS"),
java("yyyy-MM-dd HH:mm:ss.S"),
]
};
let rows: Vec<ConsumerRow> = vec![
(
"2024-12-15",
vec![java("yyyy-MM-dd")],
Some(0),
None,
Some("2024-12-15T00:00:00.000Z"),
),
(
"2024-12-15",
vec![java("yyyy-MM-dd")],
Some(39_600),
None,
Some("2024-12-15T00:00:00.000+11:00"),
),
("not a date", vec![java("yyyy-MM-dd")], None, None, None),
(
"18:32:29.495",
vec![java("HH:mm:ss.SSS")],
None,
None,
Some("2026-01-01T18:32:29.495Z"),
),
(
"09:30:00",
vec![java("HH:mm:ss")],
Some(39_600),
None,
Some("2026-01-01T09:30:00.000+11:00"),
),
(
"2022-05-30T04:12:12-07:00",
vec![java("yyyy-MM-dd'T'hh:mm:ssXXX")],
None,
None,
Some("2022-05-30T07:00:00.000Z"),
),
(
"Jun 11 09:30:00",
vec![java("MMM d HH:mm:ss")],
None,
None,
Some("2026-06-11T09:30:00.000Z"),
),
(
"2016-02-29 10:42:23-0700",
vec![java(FRACTIONS)],
None,
None,
Some("2016-02-29T17:42:23.000Z"),
),
(
"2020-01-16 08:00:31",
vec![java("YYYY-dd-MM HH:mm:ss")],
Some(0),
None,
Some("2019-12-29T08:00:31.000Z"),
),
(
"2019-01-01:01:01.000Z",
vec![java("yyyy-MM-dd:HH:mm.SSSz")],
None,
None,
Some("2019-01-01T00:00:00.000Z"),
),
(
"Oct 10 2018 12:34:56",
[iso(), vec![java(CISCO)]].concat(),
Some(0),
None,
Some("2018-10-10T12:34:56.000Z"),
),
(
"May 5 17:51:17",
[iso(), vec![java(CISCO)]].concat(),
Some(0),
None,
Some("2026-05-05T17:51:17.000Z"),
),
(
"20250116",
vec![java("yyyyMMdd")],
None,
None,
Some("2025-01-16T00:00:00.000Z"),
),
(
"2025-01-16T04:05:06Z",
iso(),
None,
Some(RenderFormat::Date),
Some("2025-01-16"),
),
(
"2023-05-21 09:58:40.25",
fractions(),
Some(0),
None,
Some("2023-05-21T09:58:40.250Z"),
),
(
"1587230269",
vec![seconds.clone(), millis.clone()],
None,
None,
Some("2020-04-18T17:17:49.000Z"),
),
(
"1736935526000",
vec![millis.clone()],
None,
None,
Some("2025-01-15T10:05:26.000Z"),
),
(
"1742799479.852",
vec![seconds.clone()],
None,
None,
Some("2025-03-24T06:57:59.852Z"),
),
(
"0",
vec![millis],
None,
None,
Some("1970-01-01T00:00:00.000Z"),
),
(
"-86400",
vec![seconds],
None,
None,
Some("1969-12-31T00:00:00.000Z"),
),
(
"2023 May 2 12:55:19",
vec![java("yyyy MMM d HH:mm:ss")],
Some(36_000),
None,
Some("2023-05-02T12:55:19.000+10:00"),
),
(
"2023 May 2 12:55:19",
vec![java("yyyy MMM d HH:mm:ss")],
Some(0),
None,
Some("2023-05-02T12:55:19.000Z"),
),
(
"2023-05-02 12:55:19 -0500",
vec![java("yyyy-MM-dd HH:mm:ss Z")],
Some(36_000),
None,
Some("2023-05-02T17:55:19.000Z"),
),
(
"2021-05-26T16:26:47.123456789Z",
iso(),
None,
None,
Some("2021-05-26T16:26:47.123Z"),
),
(
"2025-03-01",
iso(),
None,
None,
Some("2025-03-01T00:00:00.000Z"),
),
(
"2024-07-01T10:48:39.852Z",
iso(),
None,
Some(RenderFormat::EpochMillis),
Some("1719830919852"),
),
(
"2025-04-16T03:01:01.1951498Z",
iso(),
None,
Some(RenderFormat::Rfc3339(Fraction::Trimmed(3))),
Some("2025-04-16T03:01:01.1951498Z"),
),
(
"2024-07-01T10:48:39.852Z",
iso(),
None,
Some(printer("yyyy-MM-dd HH:mm:ss")),
Some("2024-07-01 10:48:39"),
),
(
"abcdefghi\u{3a9}2024-12-15 09:30:00",
vec![java("'abcdefghi\u{3a9}'yyyy-MM-dd HH:mm:ss")],
Some(36_000),
None,
Some("2024-12-15T09:30:00.000+10:00"),
),
(
"1969-12-31T23:59:58.250Z",
iso(),
None,
Some(RenderFormat::EpochSeconds),
Some("-1.75"),
),
(
"2024-07-17T12:05:32,104",
iso(),
None,
None,
Some("2024-07-17T12:05:32.104Z"),
),
("2024-07-17,12:05:32", iso(), None, None, None),
(
"24/10/23 7:07:31",
vec![java("dd/MM/yyyy H:mm:ss"), java("dd/MM/yy H:mm:ss")],
Some(-25_200),
None,
Some("2023-10-24T07:07:31.000-07:00"),
),
(
"2025-03-19 05:33:45.9196243 +0000 UTC",
vec![java("yyyy-MM-dd HH:mm:ss.n Z z")],
None,
None,
Some("2025-03-19T05:33:45.009Z"),
),
(
"2013-07-01 11:27:23 PST",
vec![java("yyyy-MM-dd HH:mm:ss z")],
None,
None,
Some("2013-07-01T19:27:23.000Z"),
),
];
let failed: Vec<String> = rows
.iter()
.filter_map(|(input, formats, secs, output, want)| {
let zone = secs.map(zone_at);
let got = consumer_date(input, formats, zone.as_ref(), output.as_ref());
(got.as_deref() != *want).then(|| format!("{input:?} {secs:?}: {got:?}, want {want:?}"))
})
.collect();
assert!(failed.is_empty(), "{failed:#?}");
}
#[test]
fn a_render_format_built_from_text_fails_at_build() {
use StrptimeDialect::{Java, Jiff, PercentL};
let built = RenderFormat::strftime;
assert_eq!(
built(Jiff, "%Y-%m-%d").unwrap(),
RenderFormat::Strftime("%Y-%m-%d".into())
);
assert_eq!(
built(PercentL, "%H:%M:%S.%L").unwrap(),
RenderFormat::Strftime("%H:%M:%S.%f".into())
);
assert!(matches!(
built(Java, "yyyy-MM-dd").unwrap(),
RenderFormat::Java(_)
));
for (dialect, text) in [(Jiff, "%+"), (Jiff, "%Y %"), (PercentL, "%Z")] {
assert!(
matches!(built(dialect, text), Err(TimeError::Directive(_))),
"{dialect:?} {text}"
);
}
assert!(matches!(
built(Java, "yyyy QQ"),
Err(TimeError::Pattern { .. })
));
}
#[test]
fn a_format_cache_builds_each_text_once() {
use StrptimeDialect::{Java, Jiff};
use std::sync::Arc;
let cache = FormatCache::new(2);
assert!(cache.is_empty());
let first = cache.time_format(Java, "yyyy-MM-dd").unwrap();
let again = cache.time_format(Java, "yyyy-MM-dd").unwrap();
assert!(Arc::ptr_eq(&first, &again));
let other = cache.time_format(Jiff, "yyyy-MM-dd").unwrap();
assert!(!Arc::ptr_eq(&first, &other));
assert_eq!(*other, TimeFormat::Strptime("yyyy-MM-dd".into()));
assert!(cache.time_format(Java, "yyyy QQ").is_err());
assert_eq!(cache.len(), (1, 0));
let year = cache.render_format(Jiff, "%Y").unwrap();
assert!(Arc::ptr_eq(
&year,
&cache.render_format(Jiff, "%Y").unwrap()
));
// Past the limit a text is built each time and not kept.
cache.time_format(Jiff, "%H").unwrap();
let past = cache.time_format(Jiff, "%M").unwrap();
assert!(!Arc::ptr_eq(&past, &cache.time_format(Jiff, "%M").unwrap()));
assert_eq!((cache.len(), cache.limit()), ((2, 1), 2));
assert_eq!(FormatCache::default().limit(), FormatCache::DEFAULT_LIMIT);
let shared = FormatCache::default();
std::thread::scope(|s| {
for _ in 0..4 {
s.spawn(|| {
for i in 0..50 {
let text = format!("%Y {}", i % 10);
assert!(shared.time_format(Jiff, &text).is_ok());
}
});
}
});
assert_eq!(shared.len(), (10, 0));
}
/// Formats from a consumer's corpus, one per line before a tab, in the file
/// the environment variable `var` names. `None` when it isn't set: the corpus
/// stays out of this repository.
fn date_corpus(var: &str) -> Option<Vec<String>> {
let path = std::env::var_os(var)?;
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{var}: {e}"));
let formats: Vec<String> = text
.lines()
.filter_map(|l| l.split('\t').next())
.filter(|f| !f.is_empty())
.map(str::to_owned)
.collect();
assert!(!formats.is_empty(), "{var} names a file with no formats");
Some(formats)
}
/// Every Java-style pattern in the corpus builds, prints an instant, and
/// reads back what it printed, but for the named words that aren't patterns.
#[test]
fn the_java_date_corpus_builds_and_prints() {
let Some(formats) = date_corpus("GRIPPO_JAVA_DATE_FORMATS") else {
return;
};
let ts = utc("2026-11-30T10:00:01.123Z");
let d = TimeDefaults {
now: Some(ts),
..TimeDefaults::default()
};
let mut refused = Vec::new();
let mut unread = Vec::new();
for text in &formats {
let Ok(format) = TimeFormat::strptime(StrptimeDialect::Java, text) else {
refused.push(text.as_str());
continue;
};
let printed = render(ts, &printer(text), &TimeZone::UTC).unwrap();
if let Err(e) = parse_stamp(&format, printed.as_bytes(), &d) {
unread.push(format!("{text} printed {printed:?}: {e}"));
}
}
assert!(unread.is_empty(), "{unread:#?}");
let named = |t: &&&str| t.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
let odd: Vec<&&str> = refused.iter().filter(|t| !named(t)).collect();
assert!(odd.is_empty(), "{odd:?}");
}
/// Every strftime format in the corpus builds to write, but for `%+`,
/// which jiff doesn't define.
#[test]
fn the_strftime_date_corpus_builds() {
let Some(formats) = date_corpus("GRIPPO_STRFTIME_DATE_FORMATS") else {
return;
};
let failed: Vec<&String> = formats
.iter()
.filter(|text| !text.contains("%+"))
.filter(|text| RenderFormat::strftime(StrptimeDialect::Jiff, text).is_err())
.collect();
assert!(failed.is_empty(), "{failed:?}");
}
/// Elasticsearch 9.2.2's `ISO8601` and a java.time `SSS`, run on the same
/// rows: upper-case `T` and `Z` only, and exactly three fraction digits.
#[test]
fn strict_readings_refuse_what_elasticsearch_refuses() {
let d = TimeDefaults::default();
let iso = |format: &TimeFormat, text: &str| parse_time(format, text.as_bytes(), &d).is_ok();
for (text, strict) in [
("2026-11-30T10:00:00", true),
("2026-11-30T10:00:00,5Z", true),
("2026-11-30T10:00:00+1000", true),
("2026-11-30T10:00:00+10", true),
("2026-11-30T10:00Z", true),
("2026-11-30t10:00:00z", false),
("2026-11-30T10:00:00z", false),
("2026-11-30t10:00:00Z", false),
("2026-11-30 10:00:00Z", false),
("2026-12-31T23:59:60Z", false),
] {
assert_eq!(iso(&TimeFormat::Iso8601Strict, text), strict, "{text}");
assert_eq!(
iso(&TimeFormat::Iso8601, text),
text != "2026-12-31T23:59:60Z",
"{text}, the default"
);
}
let pattern = "yyyy-MM-dd HH:mm:ss.SSS";
let strict = TimeFormat::strptime(StrptimeDialect::JavaStrict, pattern).unwrap();
let loose = TimeFormat::strptime(StrptimeDialect::Java, pattern).unwrap();
for (text, reads) in [
("2024-12-15 09:30:40.250", true),
("2024-12-15 09:30:40.25", false),
("2024-12-15 09:30:40.2", false),
("2024-12-15 09:30:40.2500", false),
] {
assert_eq!(iso(&strict, text), reads, "{text}");
assert!(iso(&loose, text), "{text}, Java reads any count");
}
assert_eq!(
parse_time(&strict, b"2024-12-15 09:30:40.250", &d).ok(),
parse_time(&loose, b"2024-12-15 09:30:40.250", &d).ok()
);
}
proptest::proptest! {
/// The `i64` epoch path gives the 128-bit path's answer, errors included.
#[test]
fn small_epochs_read_as_the_wide_path_does(
whole in "[0-9]{1,18}",
frac in "[0-9]{0,12}",
neg in proptest::bool::ANY,
unit in proptest::sample::select(vec![
EpochUnit::Seconds,
EpochUnit::Millis,
EpochUnit::Micros,
EpochUnit::Nanos,
EpochUnit::Auto,
]),
) {
let (w, f) = (whole.as_bytes(), frac.as_bytes());
let small = epoch_small(w, f, unit, neg).ok();
let wide = epoch_wide(w, f, unit, neg).ok();
proptest::prop_assert_eq!(small, wide, "{}{}.{} {:?}", if neg { "-" } else { "" }, whole, frac, unit);
}
}
/// What chrono 0.4.45 makes of `input` in `format`: nanoseconds since the
/// epoch, and the offset the text named. Text with no offset is placed `tz`
/// seconds east, as `Parsed::to_datetime_with_timezone` places it.
fn chrono_reads(format: &str, input: &str, tz: i32) -> Option<(i128, Option<i32>)> {
use chrono::FixedOffset;
use chrono::format::{Parsed, StrftimeItems, parse};
let total = |secs: i64, nanos: u32| i128::from(secs) * 1_000_000_000 + i128::from(nanos);
let mut parsed = Parsed::new();
parse(&mut parsed, input, StrftimeItems::new(format)).ok()?;
if let Some(offset) = parsed.offset() {
let at = parsed.to_datetime().ok()?;
Some((
total(at.timestamp(), at.timestamp_subsec_nanos()),
Some(offset),
))
} else {
let at = parsed
.to_datetime_with_timezone(&FixedOffset::east_opt(tz)?)
.ok()?;
Some((total(at.timestamp(), at.timestamp_subsec_nanos()), None))
}
}
/// What `StrptimeDialect::Chrono` makes of `input` in `format`, the same way.
fn chrono_dialect_reads(format: &str, input: &str, tz: i32) -> Option<(i128, Option<i32>)> {
let format = TimeFormat::strptime(StrptimeDialect::Chrono, format).ok()?;
let defaults = TimeDefaults {
zone: TimeZone::fixed(Offset::from_seconds(tz).ok()?),
..TimeDefaults::default()
};
let stamp = parse_stamp(&format, input.as_bytes(), &defaults).ok()?;
Some((
stamp.timestamp.as_nanosecond(),
stamp.offset.map(Offset::seconds),
))
}
/// How the chrono dialect and chrono read `input` apart, if they do. Text
/// chrono reads in a year past jiff's is left out, as no instant here holds it.
fn disagreement(format: &str, input: &str, tz: i32) -> Option<String> {
let theirs = chrono_reads(format, input, tz);
if theirs.is_some_and(|(ns, _)| Timestamp::from_nanosecond(ns).is_err()) {
return None;
}
let ours = chrono_dialect_reads(format, input, tz);
(ours != theirs).then(|| format!("{format:?} {input:?}: grippo {ours:?}, chrono {theirs:?}"))
}
/// Rows from chrono 0.4.45's own tests: `Ok(dt)` and `is_err` in
/// src/datetime/tests.rs:1159-1300, where `dt` is 2013-08-09T23:54:35-09:00.
/// Each is `(format, input, chrono reads it)`.
const ZONE_ROWS: &[(&str, &str, bool)] = &[
("%b %d %Y %H:%M:%S %z", "Aug 09 2013 23:54:35 -0900", true),
("%b %d %Y %H:%M:%S %z", "Aug 09 2013 23:54:35 -09 00", true),
("%b %d %Y %H:%M:%S %z", "Aug 09 2013 23:54:35 -09:00", true),
(
"%b %d %Y %H:%M:%S %z",
"Aug 09 2013 23:54:35 -09 : 00",
true,
),
("%b %d %Y %H:%M:%S -%z", "Aug 09 2013 23:54:35 --0900", true),
("%b %d %Y %H:%M:%S +%z", "Aug 09 2013 23:54:35 +-0900", true),
(
"%b %d %Y %H:%M:%S %z ",
"Aug 09 2013 23:54:35 -09:00 ",
true,
),
(
"%b %d %Y %H:%M:%S %z",
"Aug 09 2013 23:54:35 -09:00\n",
false,
),
(
"%b %d %Y %H:%M:%S %z ",
"Aug 09 2013 23:54:35 -09:00\n",
true,
),
(
"%b %d %Y %H:%M:%S %z",
"Aug 09 2013 23:54:35 -09:00:",
false,
),
(
"%b %d %Y %H:%M:%S %z ",
"Aug 09 2013 23:54:35 -09:00: ",
false,
),
(
"%b %d %Y %H:%M:%S %z ",
"Aug 09 2013 23:54:35 -09:00:",
false,
),
("%b %d %Y %H:%M:%S %z", "Aug 09 2013 23:54:35 -09", false),
("%b %d %Y %H:%M:%S %z", "Aug 09 2013 23:54:35 -09::00", true),
(
"%b %d %Y %H:%M:%S %z::",
"Aug 09 2013 23:54:35 -0900::",
true,
),
(
"%b %d %Y %H:%M:%S %z:00",
"Aug 09 2013 23:54:35 -09:00:00",
true,
),
(
"%b %d %Y %H:%M:%S %z:00 ",
"Aug 09 2013 23:54:35 -09:00:00 ",
true,
),
(
"%b %d %Y %H:%M:%S %:z",
"Aug 09 2013 23:54:35 -09:00",
true,
),
("%b %d %Y %H:%M:%S %:z", "Aug 09 2013 23:54:35 -0900", true),
("%b %d %Y %H:%M:%S %:z", "Aug 09 2013 23:54:35 -09 00", true),
(
"%b %d %Y %H:%M:%S %:z",
"Aug 09 2013 23:54:35 -09 : 00",
true,
),
(
"%b %d %Y %H:%M:%S %:z:",
"Aug 09 2013 23:54:35 -09 : 00:",
true,
),
("%b %d %Y %H:%M:%S %:z", "Aug 09 2013 23:54:35 -09", false),
(
"%b %d %Y %H:%M:%S %:z",
"Aug 09 2013 23:54:35 -09::00",
true,
),
(
"%b %d %Y %H:%M:%S %:z",
"Aug 09 2013 23:54:35 -09:00:",
false,
),
(
"%b %d %Y %H:%M:%S %:z",
"Aug 09 2013 23:54:35 -09:00::",
false,
),
(
"%b %d %Y %H:%M:%S %:z::",
"Aug 09 2013 23:54:35 -09:00::",
true,
),
("%b %d %Y %H:%M:%S %::z", "Aug 09 2013 23:54:35 -0900", true),
(
"%b %d %Y %H:%M:%S %::z",
"Aug 09 2013 23:54:35 -09:00",
true,
),
(
"%b %d %Y %H:%M:%S %::z",
"Aug 09 2013 23:54:35 -09 : 00",
true,
),
(
"%b %d %Y %H:%M:%S %::z",
"Aug 09 2013 23:54:35 -09:00:00",
false,
),
(
"%b %d %Y %H:%M:%S %::z",
"Aug 09 2013 23:54:35 -09::00",
true,
),
(
"%b %d %Y %H:%M:%S %:z",
"Aug 09 2013 23:54:35 -09::00",
true,
),
("%b %d %Y %H:%M:%S %::z", "Aug 09 2013 23:54:35 -09", false),
(
"%b %d %Y %H:%M:%S %::z1234",
"Aug 09 2013 23:54:35 -09001234",
true,
),
(
"%b %d %Y %H:%M:%S %::z1234",
"Aug 09 2013 23:54:35 -09:001234",
true,
),
(
"%b %d %Y %H:%M:%S %::z ",
"Aug 09 2013 23:54:35 -0900 ",
true,
),
(
"%b %d %Y %H:%M:%S %::z\t\n",
"Aug 09 2013 23:54:35 -0900\t\n",
true,
),
(
"%b %d %Y %H:%M:%S %::z:",
"Aug 09 2013 23:54:35 -0900:",
true,
),
(
"%b %d %Y %H:%M:%S :%::z:0",
"Aug 09 2013 23:54:35 :-0900:0",
true,
),
(
"%b %d %Y %H:%M:%S :%::z::",
"Aug 09 2013 23:54:35 :-0900: ",
false,
),
(
"%b %d %Y %::z: %H:%M:%S",
"Aug 09 2013 -0900: 23:54:35",
true,
),
(
"%b %d %Y :%::z:0 %H:%M:%S",
"Aug 09 2013 :-0900:0 23:54:35",
true,
),
(
"%b %d %Y :%::z %H:%M:%S",
"Aug 09 2013 :-0900: 23:54:35",
false,
),
(
"%b %d %Y %H:%M:%S %::z ",
"Aug 09 2013 23:54:35 -09:00:00 ",
false,
),
(
"%b %d %Y %H:%M:%S %:::z",
"Aug 09 2013 23:54:35 -09:00",
true,
),
(
"%b %d %Y %H:%M:%S %:::z",
"Aug 09 2013 23:54:35 -0900",
true,
),
(
"%b %d %Y %H:%M:%S %:::z ",
"Aug 09 2013 23:54:35 -0900 ",
true,
),
("%b %d %Y %H:%M:%S %:::z", "Aug 09 2013 23:54:35 -09", false),
(
"%b %d %Y %H:%M:%S %::::z",
"Aug 09 2013 23:54:35 -0900",
false,
),
(
"%b %d %Y %H:%M:%S %::::z",
"Aug 09 2013 23:54:35 -09:00",
false,
),
("%b %d %Y %H:%M:%S %#z", "Aug 09 2013 23:54:35 -09:00", true),
("%b %d %Y %H:%M:%S %#z", "Aug 09 2013 23:54:35 -0900", true),
(
"%b %d %Y %H:%M:%S %#z ",
"Aug 09 2013 23:54:35 -09:00 ",
true,
),
(
"%b %d %Y %H:%M:%S %#z ",
"Aug 09 2013 23:54:35 -0900 ",
true,
),
("%b %d %Y %H:%M:%S %#z", "Aug 09 2013 23:54:35 -09", true),
("%b %d %Y %H:%M:%S %#z", "Aug 09 2013 23:54:35 -09:", true),
("%b %d %Y %H:%M:%S %#z ", "Aug 09 2013 23:54:35 -09: ", true),
("%b %d %Y %H:%M:%S+%#z", "Aug 09 2013 23:54:35+-09", true),
("%b %d %Y %H:%M:%S-%#z", "Aug 09 2013 23:54:35--09", true),
("%b %d %Y %#z%H:%M:%S", "Aug 09 2013 -09:00 23:54:35", true),
("%b %d %Y %#z%H:%M:%S", "Aug 09 2013 -0900 23:54:35", true),
("%b %d %Y %#z%H:%M:%S", "Aug 09 2013 -090023:54:35", true),
("%b %d %Y %#z%H:%M:%S", "Aug 09 2013 -09:0023:54:35", true),
(
"%b %d %Y %H:%M:%S %#z",
"Aug 09 2013 23:54:35 -09:00:00",
false,
),
("%b %d %Y %H:%M:%S %#z", "Aug 09 2013 23:54:35 -090", false),
(
"%b %d %Y %H:%M:%S %#z ",
"Aug 09 2013 23:54:35 -090 ",
false,
),
("%b %d %Y %#z %H:%M:%S", "Aug 09 2013 -090 23:54:35", false),
(
"%b %d %Y %#z %H:%M:%S",
"Aug 09 2013 -09:00:00 23:54:35",
false,
),
("%b %d %Y %#z%H:%M:%S", "Aug 09 2013 -09:00:23:54:35", false),
];
/// Rows from src/naive/datetime/tests.rs:228-262, the white space a format
/// and its text may differ by, where `dt` is 2013-08-09T23:54:35.
const SPACE_ROWS: &[(&str, &str, bool)] = &[
(" %b %d %Y %H:%M:%S", " Aug 09 2013 23:54:35", true),
("%b %d %Y %H:%M:%S ", "Aug 09 2013 23:54:35 ", true),
(" %b %d %Y %H:%M:%S ", " Aug 09 2013 23:54:35 ", true),
(" %b %d %Y %H:%M:%S", " Aug 09 2013 23:54:35", true),
(" %b %d %Y %H:%M:%S", " Aug 09 2013 23:54:35", true),
(
"\n\t%b %d %Y %H:%M:%S ",
"\n\tAug 09 2013 23:54:35 ",
true,
),
("\t%b %d %Y %H:%M:%S\t", "\tAug 09 2013 23:54:35\t", true),
("%b %d %Y %H:%M:%S", "Aug 09 2013 23:54:35", true),
("%b %d %Y %H:%M:%S", "Aug 09 2013 23:54:35", true),
("%b %d %Y\t%H:%M:%S", "Aug 09 2013\t23:54:35", true),
("%b %d %Y\t\t%H:%M:%S", "Aug 09 2013\t\t23:54:35", true),
("%b %d %Y %H:%M:%S\n", "Aug 09 2013 23:54:35 ", true),
("%b %d %Y\t%H:%M:%S", "Aug 09 2013 23:54:35", true),
("%b %d %Y %H:%M:%S ", "Aug 09 2013 23:54:35", true),
(" %b %d %Y %H:%M:%S", "Aug 09 2013 23:54:35", true),
("%b %d %Y %H:%M:%S\n", "Aug 09 2013 23:54:35", true),
("%b %d %Y %H:%M:%S", " Aug 09 2013 23:54:35", false),
("%b %d %Y %H:%M:%S", "Aug 09 2013 23:54:35 ", false),
("%b %d %Y %H:%M:%S", "Aug 09 2013 23:54:35\t", false),
("%b %d %Y %H:%M:%S\n", "\nAug 09 2013 23:54:35", false),
("%b %d %Y %H:%M:%S ", "Aug 09 2013 23:54:35 !!!", false),
];
/// Rows from `test_parse_datetime_utc` in src/datetime/tests.rs:1016 and
/// `test_datetime_from_str` in src/naive/datetime/tests.rs, read through `%+`
/// and the formats those readers are built from.
const RFC3339_ROWS: &[(&str, &str, bool)] = &[
("%+", "2001-02-03T04:05:06Z", true),
("%+", "2001-02-03T04:05:06+0000", true),
("%+", "2001-02-03T04:05:06-00:00", true),
("%+", "2001-02-03T04:05:06-01:00", true),
("%+", "2012-12-12 12:12:12Z", true),
("%+", "2012-12-12t12:12:12Z", true),
("%+", "2012 -12-12T12:12:12Z", true),
("%+", "2012 -12-12T12:12:12Z", true),
("%+", "2012- 12-12T12:12:12Z", true),
("%+", "2012- 12-12T12:12:12Z", true),
("%+", "2012-12-12T 12:12:12Z", true),
("%+", "2012-12-12T12 :12:12Z", true),
("%+", "2012-12-12T12 :12:12Z", true),
("%+", "2012-12-12T12: 12:12Z", true),
("%+", "2012-12-12T12: 12:12Z", true),
("%+", "2012-12-12T12 : 12:12Z", true),
("%+", " 2012-12-12T12:12:12Z", true),
("%+", "2015-02-18T23:16:09.153Z", true),
("%+", "2015-2-18T23:16:09.153Z", true),
("%+", "+2015-2-18T23:16:09.153Z", true),
("%+", "-77-02-18T23:16:09Z", true),
("%+", "2012-12-12T12:12:12Z ", false),
("%+", "", false),
("%+", "Z", false),
("%+", "15Z", false),
("%+", "15:8:9Z", false),
("%+", "15-8-9Z", false),
("%+", "Fri, 09 Aug 2013 23:54:35 GMT", false),
("%+", "1441497364.649", false),
("%+", "+1441497364Z", false),
("%+", "2014/02/03 04:05:06Z", false),
("%+", "2001-02-03T04:05:0600:00", false),
("%+", "2015-15-15T15:15:15Z", false),
("%+", "2012-12-12T12:12:12x", false),
("%+", "2012-123-12T12:12:12Z", false),
("%+", "2012-12-77T12:12:12Z", false),
("%+", "2012-12-12T26:12:12Z", false),
("%+", "2012-12-12T12:61:12Z", false),
("%+", "2012-12-12T12:12:62Z", false),
("%+", "2012-12-12 T12:12:12Z", false),
("%+", "2012-12-12T12:12:12ZZ", false),
("%+", "+ 2012-12-12T12:12:12Z", false),
("%FT%T", "2012-12-12T12:12:12", true),
("%FT%T", "2015-15-15T15:15:15", false),
("%FT%T", "2012-12-12t12:12:12", false),
("%FT%T", "2012-12-12 12:12:12", false),
("%FT%T", "2012-12-12T12:12:12Z", false),
("%FT%T", "2012-12-12T12:12:12+00:00", false),
("%FT%T", "+ 82701-123-12T12:12:12", false),
("%FT%T", "+802701-123-12T12:12:12", false),
("%FT%T", "Sat Jun 30 23:59:60 2012", false),
("%FT%T", "2014/02/03 04:05:06", false),
];
/// Rows with the instant each reads as, from chrono's tests and from the
/// quirks the dialect carries.
const INSTANT_ROWS: &[(&str, &str, Option<&str>)] = &[
// src/naive/datetime/tests.rs:181-225 and src/format/strftime.rs:56-64.
(
"%Y-%m-%dT%H:%M:%S%z",
"2014-5-7T12:34:56+09:30",
Some("2014-05-07T03:04:56Z"),
),
(
"%G-W%V-%u%H%M%S",
"2015-W06-1 000000",
Some("2015-02-02T00:00:00Z"),
),
(
"%a, %d %b %Y %H:%M:%S GMT",
"Fri, 09 Aug 2013 23:54:35 GMT",
Some("2013-08-09T23:54:35Z"),
),
(
"%a, %d %b %Y %H:%M:%S GMT",
"Sat, 09 Aug 2013 23:54:35 GMT",
None,
),
("%Y-%m-%d Q%q %H:%M:%S", "2014-5-7 Q2 12:3456", None),
("%H:%M:%S", "12:34:56", None),
("%s", "1441497364", Some("2015-09-05T23:56:04Z")),
(
"%s.%f",
"1283929614.1234",
Some("2010-09-08T07:06:54.000001234Z"),
),
("%s%.3f", "1441497364.649", Some("2015-09-05T23:56:04.649Z")),
(
"%s%.6f",
"1497854303.087654",
Some("2017-06-19T06:38:23.087654Z"),
),
(
"%s%.9f",
"1437742189.918273645",
Some("2015-07-24T12:49:49.918273645Z"),
),
("%s%.3f", "1441497364.6495", None),
("%s%.9f", "1437742189.918273", None),
// `%f` is a count of nanoseconds, `%.f` a fraction.
(
"%Y-%m-%d %H:%M:%S.%f",
"2026-11-30 10:00:01.5",
Some("2026-11-30T10:00:01.000000005Z"),
),
(
"%Y-%m-%d %H:%M:%S%.f",
"2026-11-30 10:00:01.5",
Some("2026-11-30T10:00:01.5Z"),
),
(
"%Y-%m-%d %H:%M:%S%.f",
"2026-11-30 10:00:01.1234567891",
Some("2026-11-30T10:00:01.123456789Z"),
),
// `%3f`, `%6f` and `%9f` read exactly that many digits.
(
"%Y-%m-%dT%H:%M:%S.%3fZ",
"2024-03-15T08:00:15.500Z",
Some("2024-03-15T08:00:15.5Z"),
),
(
"%Y-%m-%dT%H:%M:%S.%3fZ",
"2024-01-15T09:00:01.000000000Z",
None,
),
("%Y-%m-%dT%H:%M:%S.%9fZ", "2024-03-15T08:00:15.500Z", None),
(
"%Y-%m-%dT%H:%M:%S%.3f%:z",
"2024-01-15T09:00:01+00:00",
Some("2024-01-15T09:00:01Z"),
),
(
"%Y-%m-%dT%H:%M:%S%.3f%:z",
"2024-01-15T09:00:01.123456+00:00",
None,
),
// `%:z` reads no seconds, and `%z` takes a colon, a space or neither.
(
"%Y-%m-%d %H:%M:%S %:z",
"2026-11-30 10:00:00 -03:15:20",
None,
),
("%m-%d %H:%M %:z%Y", "11-30 10:00 -03:15:2059", None),
(
"%Y-%m-%d %H:%M:%S %z",
"2026-11-30 10:00:00 +09 30",
Some("2026-11-30T00:30:00Z"),
),
// `%Y` takes a sign and then digits, and `%s` no sign.
(
"%Y-%m-%d %H:%M",
"+2127-01-01 00:00",
Some("2127-01-01T00:00:00Z"),
),
("%Y-%m-%d %H:%M", "+ 2127-01-01 00:00", None),
("%Y-%m-%d", "2127-01-01", None),
("%F %T", "- 2127-01-01 00:00:00", None),
("%s", "-86400", None),
("%s", "+86400", None),
("%s", " 86400", Some("1970-01-02T00:00:00Z")),
// A time zone name sets nothing, and a leap second runs into the next minute.
(
"%b %d %Y %H:%M:%S %Z",
"Aug 09 2013 23:54:35 PST",
Some("2013-08-09T23:54:35Z"),
),
(
"%Y-%m-%d %H:%M:%S",
"2016-12-31 23:59:60",
Some("2017-01-01T00:00:00Z"),
),
(
"%Y-%m-%d %H:%M:%S%.f%z",
"2016-12-31 23:59:60.5+0000",
Some("2017-01-01T00:00:00.5Z"),
),
// A date that doesn't exist, a year with no century, and a clock with no meridiem.
("%Y-%m-%d", "2026-02-30", None),
(
"%y-%m-%d %H:%M",
"69-12-31 00:00",
Some("2069-12-31T00:00:00Z"),
),
(
"%y-%m-%d %H:%M",
"70-01-01 00:00",
Some("1970-01-01T00:00:00Z"),
),
("%I:%M %Y-%m-%d", "10:30 2026-11-30", None),
(
"%I:%M %p %Y-%m-%d",
"12:30 AM 2026-11-30",
Some("2026-11-30T00:30:00Z"),
),
// No year is an error, where the jiff dialect takes one from the defaults.
("%b %e %H:%M:%S", "Nov 30 10:00:00", None),
];
/// Text chrono reads in a year jiff has no instant for.
const BEYOND_JIFF: &[(&str, &str)] = &[
("%+", "+82701-05-6T15:9:60.898989898989Z"),
("%Y-%m-%d %H:%M", "+262142-12-31 00:00"),
("%Y-%m-%d %H:%M", "-262143-01-01 00:00"),
("%Y-%m-%d %H:%M", "+10000-01-01 00:00"),
];
#[test]
fn the_chrono_dialect_reads_chrono_own_test_rows_as_chrono_does() {
let at = |text| utc(text).as_nanosecond();
let mut failed = Vec::new();
for (rows, instant) in [
(ZONE_ROWS, Some("2013-08-10T08:54:35Z")),
(SPACE_ROWS, Some("2013-08-09T23:54:35Z")),
(RFC3339_ROWS, None),
] {
for &(format, input, reads) in rows {
let theirs = chrono_reads(format, input, 0);
if theirs.is_some() != reads {
failed.push(format!(
"{format:?} {input:?}: chrono read {theirs:?}, its test says {reads}"
));
}
failed.extend(disagreement(format, input, 0));
if let (Some(want), true) = (instant, reads) {
let got = chrono_dialect_reads(format, input, 0).map(|(ns, _)| ns);
if got != Some(at(want)) {
failed.push(format!("{format:?} {input:?}: grippo {got:?}, want {want}"));
}
}
}
}
for &(format, input, want) in INSTANT_ROWS {
let (ours, theirs) = (
chrono_dialect_reads(format, input, 0),
chrono_reads(format, input, 0),
);
let want = want.map(at);
if ours.map(|(ns, _)| ns) != want || theirs.map(|(ns, _)| ns) != want {
failed.push(format!(
"{format:?} {input:?}: grippo {ours:?}, chrono {theirs:?}, want {want:?}"
));
}
}
for &(format, input) in BEYOND_JIFF {
if chrono_reads(format, input, 0).is_none()
|| chrono_dialect_reads(format, input, 0).is_some()
{
failed.push(format!("{format:?} {input:?}: beyond jiff's years"));
}
}
assert!(failed.is_empty(), "{failed:#?}");
}
#[test]
fn the_chrono_dialect_refuses_a_format_chrono_has_no_item_for() {
for format in [
"%Q", "%E", "%5Y", "%-3f", "%#Y", "%-b", "%-D", "%.4f", "%.", "%3", "%:", "%::::z", "%",
"%Y-%", "%-%", "%_n", "%0+", "%#", "%3x", "%.3", "%6g", "%-", "%\u{e9}",
] {
assert!(
matches!(
TimeFormat::strptime(StrptimeDialect::Chrono, format),
Err(TimeError::Directive(_))
),
"{format:?} built"
);
assert!(
chrono_reads(format, "2026-11-30 10:00:00", 0).is_none(),
"chrono read {format:?}"
);
}
let built = TimeFormat::strptime(StrptimeDialect::Chrono, "%Q");
assert!(matches!(built, Err(TimeError::Directive(d)) if d == "%Q"));
// The dialect reads and doesn't write.
assert!(matches!(
RenderFormat::strftime(StrptimeDialect::Chrono, "%Y-%m-%d"),
Err(TimeError::Directive(_))
));
}
/// Formats that between them use every item chrono's `StrftimeItems` makes,
/// each one chrono can also write.
const CHRONO_FORMATS: &[&str] = &[
"%Y-%m-%d",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%dT%H:%M:%S%.f",
"%Y-%m-%dT%H:%M:%S%.3f%:z",
"%Y-%m-%dT%H:%M:%S%.6f%z",
"%Y-%m-%d %H:%M:%S.%3f",
"%Y-%m-%d %H:%M:%S.%6f %#z",
"%Y-%m-%d %H:%M:%S.%9f",
"%Y-%m-%d %H:%M:%S.%f",
"%Y%m%d%H%M%S",
"%F %T",
"%FT%T%::z",
"%FT%T%:::z",
"%a, %d %b %Y %H:%M:%S %z",
"%A, %B %d, %Y %R",
"%a %b %e %T %Y",
"%c",
"%x %X",
"%D %r",
"%v %T",
"%d/%b/%Y:%H:%M:%S %z",
"%s",
"%s%.f",
"%s %z",
"%y%m%d %H",
"%C%y-%j %H",
"%Y-%j %H:%M",
"%G-W%V-%u %H:%M:%S",
"%Y %U %w %H:%M",
"%Y %W %u %H:%M",
"%I:%M:%S %p %Y-%m-%d",
"%l:%M %P %Y-%m-%d",
"%k:%M %Y-%m-%d",
"%Y-%m-%d %H:%M:%S%.f %Z",
"%+",
"%g %V %u %H:%M",
"%Y-%m-%d %H:%M %q",
"%h %e %Y %H:%M",
"%y/%m/%d%t%H:%M%n:%S",
"%Y-%m-%d%%%H",
];
proptest::proptest! {
/// Text chrono wrote, and the same text with one character changed, reads
/// as chrono reads it in any zone.
#[test]
fn the_chrono_dialect_reads_what_chrono_writes_and_its_mutations_alike(
row in 0..CHRONO_FORMATS.len(),
secs in -30_000_000_000_i64..250_000_000_000,
nanos in 0_u32..1_000_000_000,
offset_minutes in -1439_i32..=1439,
zone_minutes in -720_i32..=720,
at in 0_usize..64,
op in 0_u8..4,
ch in proptest::sample::select(vec![
'0', '1', '9', '-', '+', ':', ' ', '.', 'Z', 'T', '/', 'x', 'a', 'P', '%', '\u{2212}', '\n',
]),
) {
use chrono::{DateTime, FixedOffset};
let format = CHRONO_FORMATS[row];
// chrono reads `%#z` but doesn't write it.
let written = DateTime::from_timestamp(secs, nanos)
.unwrap()
.with_timezone(&FixedOffset::east_opt(offset_minutes * 60).unwrap())
.format(&format.replace("%#z", "%z"))
.to_string();
let mut chars: Vec<char> = written.chars().collect();
let place = at % (chars.len() + 1);
match op {
0 => chars.insert(place, ch),
1 if place < chars.len() => {
chars.remove(place);
}
2 if place < chars.len() => chars[place] = ch,
3 if place < chars.len() => chars.insert(place, chars[place]),
_ => {}
}
let mutated: String = chars.into_iter().collect();
for text in [&written, &mutated] {
proptest::prop_assert_eq!(disagreement(format, text, zone_minutes * 60), None);
}
}
}
/// Every date-like text in the real-world corpus, in each format chrono has
/// for it, read by chrono and by the dialect the same way.
#[test]
fn the_chrono_dialect_reads_the_corpus_as_chrono_does() {
use crate::shared_tests::corpus::{Tally, for_each_record_of};
const FORMATS: &[&str] = &[
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%dT%H:%M:%S%.f",
"%Y-%m-%d %H:%M:%S%.f",
"%Y-%m-%dT%H:%M:%S%.3f",
"%Y-%m-%dT%H:%M:%S.%3f",
"%Y-%m-%dT%H:%M:%S.%6fZ",
"%Y-%m-%dT%H:%M:%S.%9fZ",
"%Y-%m-%dT%H:%M:%S%z",
"%Y-%m-%dT%H:%M:%S%:z",
"%Y-%m-%dT%H:%M:%S%.f%:z",
"%Y-%m-%dT%H:%M:%S%.f%z",
"%Y-%m-%dT%H:%M:%S%.fZ",
"%Y-%m-%d %H:%M:%S%.f %#z",
"%+",
"%d/%b/%Y:%H:%M:%S %z",
"%b %e %H:%M:%S",
"%b %e %H:%M:%S %Y",
"%a, %d %b %Y %H:%M:%S %z",
"%a, %d %b %Y %T GMT",
"%a %b %e %T %Y",
"%s",
"%s%.f",
"%Y-%m-%d",
"%m/%d/%Y",
"%m/%d/%y",
"%d/%m/%Y %H:%M",
"%FT%T",
"%c",
"%x",
"%v %T",
"%A, %B %d, %Y",
"%B %d, %Y",
"%d %B %Y",
"%Y%m%d",
"%Y%m%d%H%M%S",
"%I:%M %p",
];
let stamps = regex::Regex::new(concat!(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}[T ][0-9]{2}:[0-9]{2}:[0-9]{2}(?:[.,][0-9]+)?(?:Z|[+-][0-9]{2}:?[0-9]{2})?",
r"|[0-9]{2}/[A-Za-z]{3}/[0-9]{4}:[0-9]{2}:[0-9]{2}:[0-9]{2} [+-][0-9]{4}",
r"|[A-Z][a-z]{2} [ 0-9][0-9] [0-9]{2}:[0-9]{2}:[0-9]{2}",
r"|[A-Z][a-z]{2}, [0-9]{1,2} [A-Z][a-z]{2} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} [A-Z+0-9-]+",
r"|\b[0-9]{9,10}(?:\.[0-9]+)?\b",
r"|[0-9]{4}-[0-9]{2}-[0-9]{2}",
r"|[0-9]{1,2}/[0-9]{1,2}/[0-9]{2,4}",
))
.unwrap();
let mut tally = Tally::default();
for_each_record_of(
&[
"time",
"access",
"syslog",
"w3c",
"cri",
"cef",
"cloud-alb",
"cloud-s3",
"cloud-vpc",
],
|r| {
let Ok(line) = std::str::from_utf8(r.bytes) else {
tally.count("chrono-dialect", r, false);
return;
};
let mut texts = vec![line];
texts.extend(stamps.find_iter(line).take(6).map(|m| m.as_str()));
let mut read = false;
for text in texts {
for format in FORMATS {
for tz in [0, 36_000] {
let Some(seen) = tally.caught("chrono-dialect", r, || {
(
chrono_reads(format, text, tz),
disagreement(format, text, tz),
)
}) else {
continue;
};
read |= seen.0.is_some();
if let Some(detail) = seen.1 {
tally.problem("chrono-dialect", r, &detail);
}
}
}
}
tally.count("chrono-dialect", r, read);
},
);
tally.finish("chrono-dialect");
}