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 axum::{ extract::Path, http::{header::ACCEPT, HeaderMap, StatusCode}, response::{Html, IntoResponse, Json, Response},
Content negotiation in an Axum handler
content-negotiation
http-headers
serialization
Intermediate
8 steps
rust
use axum::{extract::Multipart, http::StatusCode, Json}; use serde::Serialize; use tokio::io::AsyncWriteExt; use uuid::Uuid;
Streaming multipart uploads in Axum
multipart
streaming
async-io
Intermediate
10 steps
python
import time from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path
Parallel file downloads with a thread pool
concurrency
thread-pool
streaming-io
Intermediate
8 steps
rust
use std::collections::HashMap; #[derive(Debug, Clone)] struct Record {
Batched aggregation with fold in Rust
iterators
fold
hashmap
Intermediate
9 steps
go
package validate import ( "fmt"
Struct validation with reflection in Go
reflection
struct-tags
validation
Intermediate
7 steps
ruby
class ParamCoercer TYPES = { integer: ->(v) { Integer(v) }, float: ->(v) { Float(v) },
Coercing request params by schema in Ruby
lambdas
type-coercion
lookup-table
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.