rust 37 lines · 7 steps

Parsing and measuring time windows in Rust

Parse RFC 3339 timestamps with chrono, then compute elapsed time, staleness, and deadlines.

Explained by highlit
1use chrono::{DateTime, Duration, FixedOffset, Utc};
2 
3#[derive(Debug)]
4pub struct EventWindow {
5 pub started_at: DateTime<FixedOffset>,
6 pub elapsed: Duration,
7 pub is_stale: bool,
8}
9 
10pub fn analyze_event(raw: &str) -> Result<EventWindow, chrono::ParseError> {
11 let started_at = DateTime::parse_from_rfc3339(raw)?;
12 let now = Utc::now().with_timezone(started_at.offset());
13 
14 let elapsed = now.signed_duration_since(started_at);
15 let is_stale = elapsed > Duration::hours(24);
16 
17 Ok(EventWindow {
18 started_at,
19 elapsed,
20 is_stale,
21 })
22}
23 
24pub fn humanize(elapsed: Duration) -> String {
25 let secs = elapsed.num_seconds().abs();
26 match secs {
27 s if s < 60 => format!("{}s", s),
28 s if s < 3_600 => format!("{}m", s / 60),
29 s if s < 86_400 => format!("{}h {}m", s / 3_600, (s % 3_600) / 60),
30 s => format!("{}d {}h", s / 86_400, (s % 86_400) / 3_600),
31 }
32}
33 
34pub fn deadline_from(raw: &str, ttl: Duration) -> Result<DateTime<Utc>, chrono::ParseError> {
35 let start = DateTime::parse_from_rfc3339(raw)?.with_timezone(&Utc);
36 Ok(start + ttl)
37}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The `?` operator lets parsing functions propagate `ParseError` without manual matching.
  2. 2Aligning timezones before subtracting avoids offset bugs when comparing timestamps.
  3. 3Match guards turn a raw seconds count into human-readable duration buckets cleanly.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing and measuring time windows in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code