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 rand::distributions::{Alphanumeric, DistString}; use rand::rngs::OsRng; #[derive(Debug, Clone, PartialEq, Eq)]
A newtype wrapper for API tokens in Rust
newtype-pattern
randomness
encapsulation
Intermediate
6 steps
python
from datetime import datetime, timezone _INTERVALS = ( ("year", 60 * 60 * 24 * 365),
Building a human-friendly time_ago helper
datetime
timezones
formatting
Intermediate
5 steps
rust
pub fn normalize_path(input: &str) -> String { let is_absolute = input.starts_with('/'); let has_trailing_slash = input.len() > 1 && input.ends_with('/'); let mut stack: Vec<&str> = Vec::new();
Normalizing filesystem paths in Rust
string-processing
stack
path-manipulation
Intermediate
8 steps
typescript
interface UserAgentInfo { browser: { name: string; version: string }; os: { name: string; version: string }; device: 'mobile' | 'tablet' | 'desktop';
Parsing a user-agent string with ordered rules
regex
parsing
pattern-matching
Intermediate
9 steps
javascript
const express = require('express'); const router = express.Router(); const db = require('../db');
Building a paginated orders page in Express
pagination
routing
sql-queries
Intermediate
7 steps
ruby
class Document < ApplicationRecord class StaleObjectError < StandardError def initialize(id) super("Document ##{id} was modified by another process")
Optimistic locking with retries in Rails
optimistic-locking
concurrency
transactions
Advanced
8 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.