Skip to main content

satellite_datetime/
tz.rs

1//! IANA-compatible time zones with DST gaps and overlaps.
2//!
3//! Data pin: **2026a-subset**. Full tzdb is not embedded (flight-hostile). Named
4//! zones use the post-2007 US Energy Policy Act rules, EU/UK last-Sunday rules,
5//! and fixed offsets. Historical transitions before those laws are not applied.
6
7use crate::earth::CivilUtc;
8use crate::error::{Error, Result};
9use crate::instant::Instant;
10use crate::julian::unix_days_from_civil;
11
12/// Pinned subset label (not a complete tzdb dump).
13pub const TZDB_VERSION: &str = "2026a-subset-us2007-eu1996-fixed";
14
15/// How a local civil time maps to UTC instants.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub enum LocalTime {
18    /// Unique mapping.
19    Unique(Instant),
20    /// Skipped at spring-forward. The civil time does not occur.
21    Gap {
22        /// Instant just before the gap (standard offset).
23        before: Instant,
24        /// Instant just after the gap (DST offset).
25        after: Instant,
26    },
27    /// Repeated at fall-back. `first` is DST, `second` is standard (later Instant).
28    Overlap {
29        /// Earlier occurrence (DST).
30        first: Instant,
31        /// Later occurrence (standard time).
32        second: Instant,
33    },
34}
35
36/// UTC offset in force in a named zone.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct ZoneOffset {
39    /// Seconds east of UTC (negative west).
40    pub seconds_east: i32,
41    /// Whether this offset is a daylight-saving offset in this zone's rules.
42    pub is_dst: bool,
43    /// Short abbreviation (e.g. `EST`).
44    pub abbr: &'static str,
45}
46
47/// A named zone in the subset.
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub enum TimeZone {
50    /// UTC (`Etc/UTC`).
51    Utc,
52    /// America/New_York (US DST 2007+).
53    AmericaNewYork,
54    /// America/Los_Angeles (US DST 2007+).
55    AmericaLosAngeles,
56    /// Europe/London (EU/UK last Sunday March/October).
57    EuropeLondon,
58    /// Europe/Paris (EU).
59    EuropeParis,
60    /// Asia/Kolkata (fixed +05:30, no DST).
61    AsiaKolkata,
62    /// Pacific/Auckland (NZ: last Sunday September / first Sunday April).
63    PacificAuckland,
64}
65
66impl TimeZone {
67    /// IANA-style identifier for this subset zone.
68    pub fn iana_name(self) -> &'static str {
69        match self {
70            Self::Utc => "UTC",
71            Self::AmericaNewYork => "America/New_York",
72            Self::AmericaLosAngeles => "America/Los_Angeles",
73            Self::EuropeLondon => "Europe/London",
74            Self::EuropeParis => "Europe/Paris",
75            Self::AsiaKolkata => "Asia/Kolkata",
76            Self::PacificAuckland => "Pacific/Auckland",
77        }
78    }
79
80    /// Look up a subset zone. Unknown names return [`Error::Unsupported`].
81    pub fn from_iana(name: &str) -> Result<Self> {
82        Ok(match name {
83            "UTC" | "Etc/UTC" | "Zulu" => Self::Utc,
84            "America/New_York" => Self::AmericaNewYork,
85            "America/Los_Angeles" => Self::AmericaLosAngeles,
86            "Europe/London" => Self::EuropeLondon,
87            "Europe/Paris" => Self::EuropeParis,
88            "Asia/Kolkata" | "Asia/Calcutta" => Self::AsiaKolkata,
89            "Pacific/Auckland" => Self::PacificAuckland,
90            _ => return Err(Error::Unsupported),
91        })
92    }
93
94    /// Offset in force at `instant`.
95    pub fn offset_at(self, instant: Instant) -> Result<ZoneOffset> {
96        match self {
97            Self::Utc => Ok(ZoneOffset {
98                seconds_east: 0,
99                is_dst: false,
100                abbr: "UTC",
101            }),
102            Self::AsiaKolkata => Ok(ZoneOffset {
103                seconds_east: 5 * 3600 + 1800,
104                is_dst: false,
105                abbr: "IST",
106            }),
107            Self::AmericaNewYork => us_offset(instant, -5 * 3600, "EST", "EDT"),
108            Self::AmericaLosAngeles => us_offset(instant, -8 * 3600, "PST", "PDT"),
109            Self::EuropeLondon => eu_offset(instant, 0, "GMT", "BST"),
110            Self::EuropeParis => eu_offset(instant, 3600, "CET", "CEST"),
111            Self::PacificAuckland => nz_offset(instant),
112        }
113    }
114
115    /// Convert an instant to local civil clock (ISO fields, no zone suffix).
116    pub fn to_local(self, instant: Instant) -> Result<(CivilUtc, ZoneOffset)> {
117        let off = self.offset_at(instant)?;
118        let shifted =
119            instant.checked_add(crate::Duration::from_seconds(off.seconds_east as i64))?;
120        let mut c = shifted.to_utc()?;
121        // Local clock is not UTC; we reuse CivilUtc as a Y-M-D h:m:s container.
122        if c.second == 60 {
123            // Leap seconds are UTC-only; show 23:59:60 UTC then apply offset as 60s add.
124            let s = instant.checked_add(crate::Duration::from_seconds(off.seconds_east as i64))?;
125            c = s.to_utc()?;
126        }
127        Ok((c, off))
128    }
129
130    /// Interpret `local` as a wall clock in this zone.
131    pub fn resolve(self, local: CivilUtc) -> Result<LocalTime> {
132        if matches!(self, Self::Utc | Self::AsiaKolkata) {
133            let off = self.offset_at(Instant::TAI_EPOCH)?;
134            return Ok(LocalTime::Unique(local_to_instant(
135                local,
136                off.seconds_east,
137            )?));
138        }
139        let std = std_seconds(self);
140        let dst = dst_seconds(self);
141        let as_std = local_to_instant(local, std)?;
142        let as_dst = local_to_instant(local, dst)?;
143        let off_std = self.offset_at(as_std)?;
144        let off_dst = self.offset_at(as_dst)?;
145        let std_ok = off_std.seconds_east == std;
146        let dst_ok = off_dst.seconds_east == dst;
147        match (std_ok, dst_ok) {
148            (true, false) => Ok(LocalTime::Unique(as_std)),
149            (false, true) => Ok(LocalTime::Unique(as_dst)),
150            (true, true) => Ok(LocalTime::Overlap {
151                first: as_dst,
152                second: as_std,
153            }),
154            (false, false) => Ok(LocalTime::Gap {
155                before: as_std,
156                after: as_dst,
157            }),
158        }
159    }
160}
161
162fn std_seconds(z: TimeZone) -> i32 {
163    match z {
164        TimeZone::AmericaNewYork => -5 * 3600,
165        TimeZone::AmericaLosAngeles => -8 * 3600,
166        TimeZone::EuropeLondon => 0,
167        TimeZone::EuropeParis => 3600,
168        TimeZone::PacificAuckland => 12 * 3600,
169        TimeZone::Utc => 0,
170        TimeZone::AsiaKolkata => 5 * 3600 + 1800,
171    }
172}
173
174fn dst_seconds(z: TimeZone) -> i32 {
175    match z {
176        TimeZone::PacificAuckland => 13 * 3600,
177        TimeZone::Utc | TimeZone::AsiaKolkata => std_seconds(z),
178        _ => std_seconds(z) + 3600,
179    }
180}
181
182fn local_to_instant(local: CivilUtc, offset_east: i32) -> Result<Instant> {
183    // Treat fields as if they were UTC, then subtract the offset to get the Instant.
184    let as_utc = local.to_instant()?;
185    as_utc.checked_sub(crate::Duration::from_seconds(offset_east as i64))
186}
187
188fn us_offset(
189    instant: Instant,
190    std: i32,
191    abbr_std: &'static str,
192    abbr_dst: &'static str,
193) -> Result<ZoneOffset> {
194    let utc = instant.to_utc()?;
195    let y = utc.year;
196    // 02:00 local standard = 07:00 UTC for EST, 10:00 UTC for PST: utc = 02:00 - std/3600
197    let spring = ymd_nth_weekday(y, 3, 0, 2); // 2nd Sunday March
198    let fall = ymd_nth_weekday(y, 11, 0, 1); // 1st Sunday November
199    let start_hour = ((2 * 3600 - std) / 3600) as u8;
200    let end_hour = ((2 * 3600 - (std + 3600)) / 3600) as u8;
201    let start = utc_hms(spring.0, spring.1, spring.2, start_hour)?;
202    let end = utc_hms(fall.0, fall.1, fall.2, end_hour)?;
203    let dst = instant >= start && instant < end;
204    Ok(ZoneOffset {
205        seconds_east: if dst { std + 3600 } else { std },
206        is_dst: dst,
207        abbr: if dst { abbr_dst } else { abbr_std },
208    })
209}
210
211fn eu_offset(
212    instant: Instant,
213    std: i32,
214    abbr_std: &'static str,
215    abbr_dst: &'static str,
216) -> Result<ZoneOffset> {
217    let utc = instant.to_utc()?;
218    let y = utc.year;
219    let march = last_weekday(y, 3, 0);
220    let oct = last_weekday(y, 10, 0);
221    // 01:00 UTC start, 01:00 UTC end (EU).
222    let start = utc_hms(march.0, march.1, march.2, 1)?;
223    let end = utc_hms(oct.0, oct.1, oct.2, 1)?;
224    let dst = instant >= start && instant < end;
225    Ok(ZoneOffset {
226        seconds_east: if dst { std + 3600 } else { std },
227        is_dst: dst,
228        abbr: if dst { abbr_dst } else { abbr_std },
229    })
230}
231
232fn nz_offset(instant: Instant) -> Result<ZoneOffset> {
233    let utc = instant.to_utc()?;
234    let y = utc.year;
235    // NZ: DST starts last Sunday of September 02:00 NZST (+12) = 14:00 UTC previous?
236    // 02:00 NZST = 02:00-12h = 14:00 UTC of previous calendar day? 02:00 +12 means local 02:00 = UTC 14:00 previous day...
237    // local = UTC + 12 ⇒ UTC = local - 12. 02:00 Sep last Sunday NZST → 14:00 UTC previous day if 02-12 negative.
238    // 02:00 - 12h = 14:00 previous day UTC.
239    let start_local = last_weekday(y, 9, 0);
240    let end_local = ymd_nth_weekday(y + 1, 4, 0, 1);
241    let start = CivilUtc::new(start_local.0, start_local.1, start_local.2, 2, 0, 0, 0)?
242        .to_instant()?
243        .checked_sub(crate::Duration::from_seconds(12 * 3600))?;
244    let end = CivilUtc::new(end_local.0, end_local.1, end_local.2, 3, 0, 0, 0)?
245        .to_instant()?
246        .checked_sub(crate::Duration::from_seconds(13 * 3600))?;
247    let dst = instant >= start && instant < end;
248    Ok(ZoneOffset {
249        seconds_east: if dst { 13 * 3600 } else { 12 * 3600 },
250        is_dst: dst,
251        abbr: if dst { "NZDT" } else { "NZST" },
252    })
253}
254
255fn utc_hms(y: i32, m: u8, d: u8, hour: u8) -> Result<Instant> {
256    CivilUtc::new(y, m, d, hour, 0, 0, 0)?.to_instant()
257}
258
259/// n-th weekday of month (0=Sunday), n>=1.
260fn ymd_nth_weekday(year: i32, month: u8, weekday: u8, n: u8) -> (i32, u8, u8) {
261    let first_wd = weekday_of(year, month, 1);
262    let mut day = 1 + (weekday as i32 - first_wd as i32 + 7) % 7;
263    day += (n as i32 - 1) * 7;
264    (year, month, day as u8)
265}
266
267fn last_weekday(year: i32, month: u8, weekday: u8) -> (i32, u8, u8) {
268    let dim = crate::earth::days_in_month(year, month).unwrap_or(30);
269    let wd = weekday_of(year, month, dim);
270    let delta = (wd as i32 - weekday as i32 + 7) % 7;
271    (year, month, dim - delta as u8)
272}
273
274fn weekday_of(year: i32, month: u8, day: u8) -> u8 {
275    // Unix day 0 = 1970-01-01 Thursday = 4
276    let z = unix_days_from_civil(year, month, day);
277    (((z + 4) % 7 + 7) % 7) as u8
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283    use crate::earth::CivilUtc;
284
285    #[test]
286    fn ny_spring_gap_2024() {
287        let z = TimeZone::AmericaNewYork;
288        let missing = CivilUtc::new(2024, 3, 10, 2, 30, 0, 0).unwrap();
289        match z.resolve(missing).unwrap() {
290            LocalTime::Gap { .. } => {}
291            other => panic!("expected gap, got {other:?}"),
292        }
293        let ok = CivilUtc::new(2024, 3, 10, 3, 30, 0, 0).unwrap();
294        match z.resolve(ok).unwrap() {
295            LocalTime::Unique(_) => {}
296            other => panic!("expected unique, got {other:?}"),
297        }
298    }
299
300    #[test]
301    fn ny_fall_overlap_2024() {
302        let z = TimeZone::AmericaNewYork;
303        let twice = CivilUtc::new(2024, 11, 3, 1, 30, 0, 0).unwrap();
304        match z.resolve(twice).unwrap() {
305            LocalTime::Overlap { first, second } => {
306                assert!(second.duration_since(first).unwrap().as_seconds() == 3600);
307            }
308            other => panic!("expected overlap, got {other:?}"),
309        }
310    }
311
312    #[test]
313    fn kolkata_fixed() {
314        let z = TimeZone::AsiaKolkata;
315        let c = CivilUtc::new(2024, 6, 1, 12, 0, 0, 0).unwrap();
316        match z.resolve(c).unwrap() {
317            LocalTime::Unique(i) => {
318                let utc = i.to_utc().unwrap();
319                assert_eq!(utc.hour, 6);
320                assert_eq!(utc.minute, 30);
321            }
322            _ => panic!("fixed offset"),
323        }
324    }
325}