Repository navigation
How to strictly parse an RFC3339 timestamp? #621
|
I'm porting an existing CBOR parser to use Jiff instead of Chrono. Parsing CBOR requires parsing RFC3339 I can make the parsing "work" using How can I easily strictly parse an RFC3339 timestamp, in a way that will reject strings that are not strictly valid, to comply with CBOR's definition? |
Replies: 1 comment
|
For RFC 3339, a space character is technically allowed (see the note): https://datatracker.ietf.org/doc/html/rfc3339#section-5.6 CBOR's definition is indeed more precise, but it is narrower and stricter than RFC 3339. So even if Jiff offered a "strict RFC 3339" mode, it wouldn't be strict enough for your use case. What you need is an RFC 4287 conformant parser, which Jiff does not provide either. Note also that parsing into a timestamp allows probably even more than you want, since it's technically RFC 9557 conformant and thus includes time zone annotation strings. See this example: https://docs.rs/jiff/latest/jiff/fmt/temporal/struct.DateTimeParser.html#example-parsing-a-timestamp-from-a-datetime-with-a-time-zone It also accepts even more things, like Similarly for use jiff::{civil::DateTime, tz::TimeZone};
fn main() -> anyhow::Result<()> {
let dt = DateTime::strptime("%Y-%02m-%dT%H:%M:%S%.fZ", "2026-08-02T17:56:05Z")?;
let ts = dt.to_zoned(TimeZone::UTC)?.timestamp();
dbg!(ts);
Ok(())
}But even with, e.g., Jiff is generally quite permissive when it comes to parsing datetimes, but it does strictly follow Temporal's ISO 8601 specification for parsing. It's just that it subsumes common specifications like RFC 3339 because there are, as you've stumbled on to, actually many different formulations of it in the wild. I think that you probably have to hand-roll your own validator here. That is, write something that validates the timestamp is in the format you want, and then you can just feed it to Jiff's Finally, I note that Chrono's implementation also accepts a |
For RFC 3339, a space character is technically allowed (see the note): https://datatracker.ietf.org/doc/html/rfc3339#section-5.6
CBOR's definition is indeed more precise, but it is narrower and stricter than RFC 3339. So even if Jiff offered a "strict RFC 3339" mode, it wouldn't be strict enough for your use case. What you need is an RFC 4287 conformant parser, which Jiff does not provide either.
Note also that parsing into a timestamp allows probably even more than you want, since it's technically RFC 9557 conformant and thus includes time zone annotation strings. See this example: https://docs.rs/jiff/latest/jiff/fmt/temporal/struct.DateTimeParser.html#example-parsing-a-timestamp-from-a…