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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The `?` operator lets parsing functions propagate `ParseError` without manual matching.
- 2Aligning timezones before subtracting avoids offset bugs when comparing timestamps.
- 3Match guards turn a raw seconds count into human-readable duration buckets cleanly.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-and-measuring-time-windows-in-rust-explained-rust-78d2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.