Skip to main content

transitous_core/
time.rs

1//! The time of a search: an instant, or a local time that means the time at
2//! the stop, like the times of the results.
3
4use std::fmt;
5use std::str::FromStr;
6
7use jiff::Timestamp;
8use jiff::civil::{Date, DateTime, Time};
9use jiff::tz::TimeZone;
10
11/// The time of a search.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum QueryTime {
14    /// An instant, like `2026-11-27T07:50:00+01:00`.
15    At(Timestamp),
16    /// A date and time in the time zone of the stop, like
17    /// `2026-11-27T07:50`.
18    Local(DateTime),
19    /// A time of today in the time zone of the stop, like `07:50`: today
20    /// also when the time has passed, never tomorrow.
21    Today(Time),
22}
23
24impl QueryTime {
25    /// The instant of this time in `zone`, with `now` for the date of
26    /// [`QueryTime::Today`].
27    ///
28    /// # Errors
29    ///
30    /// A local time beyond the times there are, as an error message.
31    pub fn in_zone(&self, zone: &TimeZone, now: Timestamp) -> Result<Timestamp, String> {
32        let datetime = match *self {
33            Self::At(timestamp) => return Ok(timestamp),
34            Self::Local(datetime) => datetime,
35            Self::Today(time) => today(zone, now).to_datetime(time),
36        };
37        datetime
38            .to_zoned_datetime(zone.clone())
39            .map(|zoned| zoned.timestamp())
40            .map_err(|error| format!("invalid time {datetime}: {error}"))
41    }
42
43    /// Whether the instant depends on the time zone.
44    pub fn is_local(&self) -> bool {
45        !matches!(self, Self::At(_))
46    }
47}
48
49fn today(zone: &TimeZone, now: Timestamp) -> Date {
50    now.to_zoned_datetime(zone.clone()).date()
51}
52
53impl From<Timestamp> for QueryTime {
54    fn from(timestamp: Timestamp) -> Self {
55        Self::At(timestamp)
56    }
57}
58
59impl FromStr for QueryTime {
60    type Err = String;
61
62    /// `HH:MM`, a local date and time, or RFC 3339 with an offset.
63    fn from_str(input: &str) -> Result<Self, String> {
64        let input = input.trim();
65        if let Ok(timestamp) = input.parse::<Timestamp>() {
66            return Ok(Self::At(timestamp));
67        }
68        // The parser of times also takes the time of a date and time, so only
69        // input without a date is a time of today.
70        let has_date = input.contains(['-', 'T', 't', ' ']);
71        if has_date && let Ok(datetime) = input.parse::<DateTime>() {
72            return Ok(Self::Local(datetime));
73        }
74        if !has_date && let Ok(time) = input.parse::<Time>() {
75            return Ok(Self::Today(time));
76        }
77        Err(format!(
78            "invalid time {input:?}: use HH:MM for today, a local time like \
79             2026-11-27T07:50, or RFC 3339 like 2026-11-27T07:50:00+01:00"
80        ))
81    }
82}
83
84impl fmt::Display for QueryTime {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        match self {
87            Self::At(timestamp) => timestamp.fmt(f),
88            Self::Local(datetime) => datetime.fmt(f),
89            Self::Today(time) => time.fmt(f),
90        }
91    }
92}
93
94/// The time zone named `name`, if it is known.
95pub(crate) fn zone(name: Option<&str>) -> Option<TimeZone> {
96    TimeZone::get(name?).ok()
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    fn now() -> Timestamp {
104        "2026-11-27T08:15:00Z".parse().unwrap()
105    }
106
107    fn berlin() -> TimeZone {
108        TimeZone::get("Europe/Berlin").unwrap()
109    }
110
111    fn resolved(input: &str, zone: &TimeZone) -> String {
112        let time: QueryTime = input.parse().unwrap();
113        time.in_zone(zone, now()).unwrap().to_string()
114    }
115
116    #[test]
117    fn reads_local_times_in_the_zone() {
118        let berlin = berlin();
119        assert_eq!(resolved("07:50", &berlin), "2026-11-27T06:50:00Z");
120        // Past times stay today.
121        assert_eq!(resolved("00:10", &berlin), "2026-11-26T23:10:00Z");
122        assert_eq!(resolved(" 23:59 ", &berlin), "2026-11-27T22:59:00Z");
123        assert_eq!(
124            resolved("2026-11-28T07:50", &berlin),
125            "2026-11-28T06:50:00Z"
126        );
127        // Summer time.
128        assert_eq!(
129            resolved("2026-07-01T07:50", &berlin),
130            "2026-07-01T05:50:00Z"
131        );
132        assert_eq!(resolved("07:50", &TimeZone::UTC), "2026-11-27T07:50:00Z");
133        // Today is the date in the zone: already the 28th in Tokyo.
134        let tokyo = TimeZone::get("Asia/Tokyo").unwrap();
135        let late: Timestamp = "2026-11-27T20:00:00Z".parse().unwrap();
136        let time: QueryTime = "07:50".parse().unwrap();
137        assert_eq!(
138            time.in_zone(&tokyo, late).unwrap().to_string(),
139            "2026-11-27T22:50:00Z"
140        );
141    }
142
143    #[test]
144    fn keeps_instants() {
145        let berlin = berlin();
146        for input in ["2026-11-28T07:50:00+01:00", "2026-11-28T06:50:00Z"] {
147            let time: QueryTime = input.parse().unwrap();
148            assert!(!time.is_local());
149            assert_eq!(resolved(input, &berlin), "2026-11-28T06:50:00Z");
150            assert_eq!(resolved(input, &TimeZone::UTC), "2026-11-28T06:50:00Z");
151        }
152        let at: Timestamp = "2026-11-28T06:50:00Z".parse().unwrap();
153        assert_eq!(QueryTime::from(at), QueryTime::At(at));
154        assert_eq!(QueryTime::from(at).to_string(), "2026-11-28T06:50:00Z");
155        assert!("07:50".parse::<QueryTime>().unwrap().is_local());
156        assert_eq!(
157            "07:50".parse::<QueryTime>().unwrap().to_string(),
158            "07:50:00"
159        );
160        let local: QueryTime = "2026-11-28T07:50".parse().unwrap();
161        assert!(local.is_local());
162        assert_eq!(local.to_string(), "2026-11-28T07:50:00");
163    }
164
165    #[test]
166    fn rejects_other_input() {
167        for input in ["", "7.50", "25:00", "tomorrow", "2026-02-30T07:50"] {
168            let error = input.parse::<QueryTime>().unwrap_err();
169            assert!(error.starts_with("invalid time"), "{input}: {error}");
170        }
171        // Beyond the last time there is.
172        let time: QueryTime = "9999-12-31T23:59".parse().unwrap();
173        let error = time.in_zone(&berlin(), now()).unwrap_err();
174        assert!(
175            error.starts_with("invalid time 9999-12-31T23:59"),
176            "{error}"
177        );
178    }
179
180    #[test]
181    fn finds_zones_by_name() {
182        assert!(zone(Some("Europe/Berlin")).is_some());
183        assert!(zone(Some("Nowhere/Else")).is_none());
184        assert!(zone(None).is_none());
185    }
186}