glacier-web 0.1.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Times in a place: a UTC timestamp shown on a hospital's (or a user's)
//! wall clock, as Rails' `in_time_zone`.

use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
use chrono_tz::Tz;

/// `at` (UTC) on the clock of `zone`, an IANA name such as
/// `"Europe/London"`; `None` for a zone it doesn't know.
pub fn in_zone(at: DateTime<Utc>, zone: &str) -> Option<DateTime<Tz>> {
    let zone: Tz = zone.parse().ok()?;
    Some(at.with_timezone(&zone))
}

/// `at` (UTC) formatted on the clock of `zone` with a `strftime` pattern,
/// as Rails' `time.in_time_zone(zone).strftime(format)`.
pub fn format_in_zone(at: DateTime<Utc>, zone: &str, format: &str) -> Option<String> {
    in_zone(at, zone).map(|local| local.format(format).to_string())
}

/// [`format_in_zone`] for a `timestamp without time zone` taken as UTC.
pub fn format_naive_in_zone(at: NaiveDateTime, zone: &str, format: &str) -> Option<String> {
    format_in_zone(at.and_utc(), zone, format)
}

/// An HTTP date (`Thu, 01 Oct 2026 10:52:12 GMT`), as Rails' `Time.parse`
/// reads one: the weekday isn't checked against the date.
pub fn parse_http_date(text: &str) -> Option<DateTime<Utc>> {
    let text = text.trim();
    let without_weekday = text.split_once(", ").map_or(text, |(_, rest)| rest);
    DateTime::parse_from_rfc2822(without_weekday)
        .or_else(|_| DateTime::parse_from_rfc2822(text))
        .ok()
        .map(|at| at.with_timezone(&Utc))
}

/// A date or time as a client sends it, read as Rails' `Time.zone.parse`
/// reads the common forms: RFC 3339 (`2026-10-05T11:00:00Z`, with its own
/// offset), or a date or date and time without one (`2026-10-05`,
/// `2026-10-05 11:00`, `2026-10-05T11:00:00.5`), on the clock of `zone`.
/// An HTTP date works too. `None` for anything else.
pub fn parse(text: &str, zone: &str) -> Option<DateTime<Utc>> {
    let text = text.trim();
    if let Ok(at) = DateTime::parse_from_rfc3339(text) {
        return Some(at.with_timezone(&Utc));
    }
    let local = [
        "%Y-%m-%dT%H:%M:%S%.f",
        "%Y-%m-%d %H:%M:%S%.f",
        "%Y-%m-%dT%H:%M",
        "%Y-%m-%d %H:%M",
    ]
    .iter()
    .find_map(|format| NaiveDateTime::parse_from_str(text, format).ok())
    .or_else(|| {
        chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d")
            .ok()
            .and_then(|date| date.and_hms_opt(0, 0, 0))
    });
    match local {
        Some(local) => local_to_utc(local, zone).map(|at| at.and_utc()),
        None => parse_http_date(text),
    }
}

/// A wall-clock time in `zone` as UTC, for storing: Rails' `end_of_day` on
/// a local time, saved. An ambiguous time (clocks going back) takes the
/// earlier; one skipped (clocks going forward) is `None`.
pub fn local_to_utc(local: NaiveDateTime, zone: &str) -> Option<NaiveDateTime> {
    let zone: Tz = zone.parse().ok()?;
    zone.from_local_datetime(&local)
        .earliest()
        .map(|at| at.naive_utc())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_as_time_zone_parse() {
        let at = |text: &str, zone: &str| parse(text, zone).map(|t| t.to_rfc3339());
        let utc = Some("2026-10-05T00:00:00+00:00".to_owned());
        assert_eq!(at("2026-10-05", "UTC"), utc);
        assert_eq!(at(" 2026-10-05 ", "Etc/UTC"), utc);
        assert_eq!(
            at("2026-10-05", "Europe/London"),
            Some("2026-10-04T23:00:00+00:00".to_owned()),
            "midnight on the zone's clock"
        );
        assert_eq!(
            at("2026-10-05T11:00:00Z", "Europe/London"),
            Some("2026-10-05T11:00:00+00:00".to_owned()),
            "an offset wins"
        );
        assert_eq!(
            at("2026-10-05 11:30", "UTC"),
            Some("2026-10-05T11:30:00+00:00".to_owned())
        );
        assert_eq!(
            at("2026-10-05T11:30:15.250", "UTC"),
            Some("2026-10-05T11:30:15.250+00:00".to_owned())
        );
        assert_eq!(at("garbage", "UTC"), None);
        assert_eq!(at("2026-13-45", "UTC"), None);
    }

    #[test]
    fn reads_http_dates_whatever_the_weekday() {
        let at = parse_http_date("Mon, 01 Jan 2030 00:00:00 GMT").unwrap();
        assert_eq!(
            at.to_rfc3339(),
            "2030-01-01T00:00:00+00:00",
            "1 Jan 2030 is a Tuesday"
        );
        assert!(parse_http_date("not a date").is_none());
    }

    #[test]
    fn stores_local_times_as_utc() {
        let local = chrono::NaiveDate::from_ymd_opt(2026, 8, 3)
            .unwrap()
            .and_hms_opt(23, 59, 59)
            .unwrap();
        assert_eq!(
            local_to_utc(local, "Europe/London").unwrap().to_string(),
            "2026-08-03 22:59:59"
        );
        assert!(local_to_utc(local, "Nowhere/Else").is_none());
    }

    #[test]
    fn shows_utc_times_on_local_clocks() {
        let at = DateTime::parse_from_rfc3339("2026-08-03T19:24:07Z")
            .unwrap()
            .to_utc();
        assert_eq!(
            format_in_zone(at, "Europe/London", "%d-%b-%Y %H:%M").as_deref(),
            Some("03-Aug-2026 20:24"),
            "British Summer Time"
        );
        let winter = DateTime::parse_from_rfc3339("2026-01-05T23:30:00Z")
            .unwrap()
            .to_utc();
        assert_eq!(
            format_in_zone(winter, "Australia/Sydney", "%d/%m/%Y").as_deref(),
            Some("06/01/2026")
        );
        assert_eq!(format_in_zone(at, "Nowhere/Special", "%Y"), None);
    }
}