raystack/
tz.rs

1use chrono_tz::{Tz, TZ_VARIANTS};
2
3/// Converts a string containing a SkySpark time zone name into the matching
4/// `Tz` variant from the chrono_tz crate.
5pub fn skyspark_tz_string_to_tz<T>(s: T) -> Option<Tz>
6where
7    T: AsRef<str>,
8{
9    let matching_tz = TZ_VARIANTS.iter().find(|tz| {
10        let full_name = tz.name();
11        let is_full_name_match = full_name == s.as_ref();
12
13        if is_full_name_match {
14            true
15        } else {
16            let short_name = time_zone_name_to_short_name(full_name);
17            short_name == s.as_ref()
18        }
19    });
20    matching_tz.copied()
21}
22
23/// Given an IANA TZDB identifier like  "America/New_York", return the
24/// short time zone name used by SkySpark (like "New_York").
25pub(crate) fn time_zone_name_to_short_name(tz_name: &str) -> &str {
26    let parts: Vec<_> = tz_name.split('/').filter(|s| !s.is_empty()).collect();
27    parts.last().expect("time zone parts should not be empty")
28}
29
30#[cfg(test)]
31mod test {
32    use super::skyspark_tz_string_to_tz;
33
34    #[test]
35    fn short_name_match_works() {
36        let tz = skyspark_tz_string_to_tz("Sydney").unwrap();
37        assert_eq!(tz, chrono_tz::Tz::Australia__Sydney);
38    }
39
40    #[test]
41    fn full_name_match_works() {
42        let tz = skyspark_tz_string_to_tz("Australia/Sydney").unwrap();
43        assert_eq!(tz, chrono_tz::Tz::Australia__Sydney);
44    }
45}