Skip to main content

goose_http/date/
mod.rs

1//! Date and time utilities for HTTP date header formatting.
2//!
3//! Provides conversions to and from IMF-fixdate as mandated by RFC 9110.
4
5use std::time::{SystemTime, UNIX_EPOCH};
6
7/// Format the provided time using the IMF-fixdate representation.
8pub fn imf_fixdate(time: SystemTime) -> String {
9    httpdate::fmt_http_date(time)
10}
11
12/// Parse an HTTP date into a `SystemTime` value.
13pub fn parse_http_date(value: &str) -> Option<SystemTime> {
14    httpdate::parse_http_date(value).ok()
15}
16
17/// Return the current time formatted as IMF-fixdate.
18pub fn now() -> String {
19    imf_fixdate(SystemTime::now())
20}
21
22/// Helper returning seconds since the Unix epoch.
23pub fn epoch_seconds(time: SystemTime) -> u64 {
24    time.duration_since(UNIX_EPOCH)
25        .unwrap_or_default()
26        .as_secs()
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    #[test]
34    fn round_trip_http_date() {
35        let original = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000);
36        let formatted = imf_fixdate(original);
37        let parsed = parse_http_date(&formatted).expect("should parse http date");
38        assert_eq!(epoch_seconds(parsed), epoch_seconds(original));
39    }
40}