time_zone/zone.rs
1//! The parsed time zone and the conversions between UTC and local civil time.
2
3use crate::civil::{DateTime, SECONDS_PER_DAY, civil_from_days};
4use crate::parse::{self, ParseError};
5use crate::rule::Rule;
6use core::fmt;
7
8/// The number of bytes of an abbreviation buffer. The longest abbreviation in
9/// tzdata 2026f is 5 bytes (`+0545`); POSIX requires at least 3 bytes.
10pub const ABBREVIATION_MAX: usize = 7;
11
12/// A zone abbreviation stored in a fixed-size ASCII buffer. The length is 0
13/// when there is no daylight saving abbreviation.
14#[derive(Clone, Copy, PartialEq, Eq)]
15pub(crate) struct Abbreviation {
16 bytes: [u8; ABBREVIATION_MAX],
17 length: u8,
18}
19
20impl Abbreviation {
21 pub(crate) const EMPTY: Self = Self {
22 bytes: [0; ABBREVIATION_MAX],
23 length: 0,
24 };
25
26 /// Store a name that the parser already validated as ASCII. Returns None
27 /// when the name does not fit the buffer.
28 pub(crate) fn from_name(name: &str) -> Option<Self> {
29 if name.len() > ABBREVIATION_MAX || !name.is_ascii() {
30 return None;
31 }
32 let mut bytes = [0; ABBREVIATION_MAX];
33 bytes[..name.len()].copy_from_slice(name.as_bytes());
34 Some(Self {
35 bytes,
36 length: name.len() as u8,
37 })
38 }
39
40 fn as_str(&self) -> &str {
41 // The parser only accepts ASCII names.
42 core::str::from_utf8(&self.bytes[..self.length as usize]).unwrap_or("")
43 }
44}
45
46impl fmt::Debug for Abbreviation {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.write_str(self.as_str())
49 }
50}
51
52/// Marks a time zone without daylight saving time in
53/// [`TimeZone::daylight_saving_offset`]. Real offsets are at most 24 hours, so
54/// this value never collides with one.
55const NO_DAYLIGHT_SAVING: i32 = i32::MIN;
56
57/// A parsed POSIX TZ string.
58///
59/// The value is `Copy`, owns its two abbreviations in fixed-size buffers and
60/// stores the two 32-bit [`Rule`] values and the two offsets inline. It is 32
61/// bytes on every target (`size_of::<TimeZone>() == 32`) and performs no
62/// allocation, so a TZ string read from settings can be parsed once and the
63/// value kept by value.
64///
65/// Offsets are seconds east of UTC, so `Europe/Paris` has a standard offset of
66/// 3600 and a daylight saving offset of 7200.
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub struct TimeZone {
69 standard_abbreviation: Abbreviation,
70 daylight_saving_abbreviation: Abbreviation,
71 standard_offset: i32,
72 /// Seconds east of UTC during daylight saving time, or
73 /// [`NO_DAYLIGHT_SAVING`] when the zone has none.
74 daylight_saving_offset: i32,
75 start: Rule,
76 end: Rule,
77}
78
79impl TimeZone {
80 /// Parse a POSIX TZ string, for example `CET-1CEST,M3.5.0,M10.5.0/3` for
81 /// `Europe/Paris`.
82 ///
83 /// The format is the `TZ` format of POSIX `tzset`:
84 /// `std offset [dst [offset] [,rule,rule]]`.
85 ///
86 /// - A name is either at least three letters (`CET`) or quoted in angle
87 /// brackets with at least three ASCII alphanumeric characters, `+` or
88 /// `-` (`<+03>`). A name longer than 7 bytes is rejected with
89 /// [`ParseError::NameTooLong`].
90 /// - An offset is `[+-]hh[:mm[:ss]]` of at most 24 hours; minutes and
91 /// seconds are 0 to 59. A bare name without an offset, for example
92 /// `UTC`, is rejected with [`ParseError::MissingOffset`].
93 /// - A rule is `Mm.w.d[/time]`, `Jn[/time]` or `n[/time]`. A rule time is a
94 /// signed `[+-]hh[:mm[:ss]]` of at most 167 hours (POSIX 2024), with
95 /// minutes and seconds of 0 to 59, and it defaults to 02:00:00.
96 /// - A daylight saving name without rules uses the United States rules
97 /// `M3.2.0/2,M11.1.0/2`, and a daylight saving offset without a value is
98 /// one hour ahead of the standard offset.
99 ///
100 /// Invalid strings return a [`ParseError`] that says which part is wrong.
101 pub fn parse(input: &str) -> Result<Self, ParseError> {
102 parse::parse(input)
103 }
104
105 /// UTC (`UTC0`) as a time zone without parsing at run time.
106 pub const fn utc() -> Self {
107 Self::fixed(
108 Abbreviation {
109 bytes: *b"UTC\0\0\0\0",
110 length: 3,
111 },
112 0,
113 )
114 }
115
116 pub(crate) const fn fixed(standard_abbreviation: Abbreviation, standard_offset: i32) -> Self {
117 Self {
118 standard_abbreviation,
119 daylight_saving_abbreviation: Abbreviation::EMPTY,
120 standard_offset,
121 daylight_saving_offset: NO_DAYLIGHT_SAVING,
122 start: Rule::implicit(crate::rule::RuleKind::MonthWeekDay, 0),
123 end: Rule::implicit(crate::rule::RuleKind::MonthWeekDay, 0),
124 }
125 }
126
127 pub(crate) const fn with_daylight_saving(
128 standard_abbreviation: Abbreviation,
129 standard_offset: i32,
130 daylight_saving_abbreviation: Abbreviation,
131 daylight_saving_offset: i32,
132 start: Rule,
133 end: Rule,
134 ) -> Self {
135 Self {
136 standard_abbreviation,
137 daylight_saving_abbreviation,
138 standard_offset,
139 daylight_saving_offset,
140 start,
141 end,
142 }
143 }
144
145 /// The abbreviation of the standard offset, for example `CET`.
146 pub fn standard_abbreviation(&self) -> &str {
147 self.standard_abbreviation.as_str()
148 }
149
150 /// The abbreviation of the daylight saving offset, if the zone has one.
151 pub fn daylight_saving_abbreviation(&self) -> Option<&str> {
152 if self.has_daylight_saving() {
153 Some(self.daylight_saving_abbreviation.as_str())
154 } else {
155 None
156 }
157 }
158
159 /// The standard offset in seconds east of UTC.
160 pub fn standard_offset_seconds(&self) -> i32 {
161 self.standard_offset
162 }
163
164 /// The daylight saving offset in seconds east of UTC, if the zone has one.
165 pub fn daylight_saving_offset_seconds(&self) -> Option<i32> {
166 if self.has_daylight_saving() {
167 Some(self.daylight_saving_offset)
168 } else {
169 None
170 }
171 }
172
173 /// Whether the zone has a daylight saving period.
174 pub fn has_daylight_saving(&self) -> bool {
175 self.daylight_saving_offset != NO_DAYLIGHT_SAVING
176 }
177
178 /// The rule that starts the daylight saving period.
179 pub fn start_rule(&self) -> Rule {
180 self.start
181 }
182
183 /// The rule that ends the daylight saving period.
184 pub fn end_rule(&self) -> Rule {
185 self.end
186 }
187
188 /// Whether daylight saving time applies at a UTC instant.
189 pub fn is_daylight_saving_at(&self, utc_seconds: i64) -> bool {
190 if !self.has_daylight_saving() {
191 return false;
192 }
193 // The rules are written in local time; pick the years around the
194 // instant so that periods that cross New Year are covered. The day
195 // split keeps the addition of the offset inside the `i64` range for
196 // every `i64` instant.
197 let day_of_utc = utc_seconds.div_euclid(SECONDS_PER_DAY);
198 let second_of_day = utc_seconds.rem_euclid(SECONDS_PER_DAY);
199 let local_days = day_of_utc
200 + (second_of_day + i64::from(self.standard_offset)).div_euclid(SECONDS_PER_DAY);
201 let year = civil_from_days(local_days).0;
202 let utc = i128::from(utc_seconds);
203 for year in [year - 1, year, year + 1] {
204 // The start time is read in standard time, the end time in
205 // daylight saving time, as POSIX tzset does.
206 let start = self.start.local_seconds(year) - i128::from(self.standard_offset);
207 let end = self.end.local_seconds(year) - i128::from(self.daylight_saving_offset);
208 if start < end {
209 if start <= utc && utc < end {
210 return true;
211 }
212 } else if start > end {
213 // The daylight saving period crosses New Year, so it ends with
214 // the end rule of the next year.
215 let end_next =
216 self.end.local_seconds(year + 1) - i128::from(self.daylight_saving_offset);
217 if utc >= start && utc < end_next {
218 return true;
219 }
220 }
221 }
222 false
223 }
224
225 /// The offset in seconds east of UTC at a UTC instant.
226 pub fn offset_at(&self, utc_seconds: i64) -> i32 {
227 if self.has_daylight_saving() && self.is_daylight_saving_at(utc_seconds) {
228 self.daylight_saving_offset
229 } else {
230 self.standard_offset
231 }
232 }
233
234 /// Convert a UTC instant, in seconds since the Unix epoch, to local time.
235 ///
236 /// The result holds the local date and time, the offset in seconds east of
237 /// UTC, the zone abbreviation and whether daylight saving time applies.
238 /// The conversion is total for every `i64` second count.
239 pub fn from_utc(&self, utc_seconds: i64) -> Local<'_> {
240 let daylight_saving = self.is_daylight_saving_at(utc_seconds);
241 let offset = if daylight_saving {
242 self.daylight_saving_offset
243 } else {
244 self.standard_offset
245 };
246 // Split the instant into day and second of day first so that adding
247 // the offset (at most 24 hours) cannot leave the `i64` range.
248 let day_of_utc = utc_seconds.div_euclid(SECONDS_PER_DAY);
249 let second_of_day_utc = utc_seconds.rem_euclid(SECONDS_PER_DAY);
250 let local_second_of_day = second_of_day_utc + i64::from(offset);
251 let days = day_of_utc + local_second_of_day.div_euclid(SECONDS_PER_DAY);
252 let second_of_day = local_second_of_day.rem_euclid(SECONDS_PER_DAY);
253 let (year, month, day) = civil_from_days(days);
254 let abbreviation = if daylight_saving {
255 self.daylight_saving_abbreviation.as_str()
256 } else {
257 self.standard_abbreviation.as_str()
258 };
259 Local {
260 date_time: DateTime {
261 year,
262 month,
263 day,
264 hour: (second_of_day / 3600) as u8,
265 minute: ((second_of_day % 3600) / 60) as u8,
266 second: (second_of_day % 60) as u8,
267 },
268 offset_seconds: offset,
269 abbreviation,
270 daylight_saving,
271 }
272 }
273
274 /// Convert a local date and time to UTC, in seconds since the Unix epoch.
275 ///
276 /// The result is explicit about repeated and missing local times:
277 /// [`LocalToUtc::Ambiguous`] for a local time that happens twice (the
278 /// repeated hour in autumn) and [`LocalToUtc::Nonexistent`] for a local
279 /// time that never happens (the skipped hour in spring).
280 ///
281 /// The input fields are not checked; see [`DateTime::is_valid`]. A local
282 /// time whose instants all fall outside the range that `i64` seconds can
283 /// hold also returns [`LocalToUtc::Nonexistent`], because no UTC instant
284 /// can represent it.
285 pub fn to_utc(&self, local: DateTime) -> LocalToUtc {
286 // A local time whose seconds count leaves the `i64` range has no
287 // representable UTC instant.
288 let Some(local_seconds) = local.unix_seconds_checked() else {
289 return LocalToUtc::Nonexistent;
290 };
291 let mut found = [0i64; 2];
292 let mut count = 0;
293 // Both offsets that the local time could use; they are equal when the
294 // zone has no daylight saving time, and the duplicate candidate below
295 // is removed.
296 let offsets = [
297 self.standard_offset,
298 if self.has_daylight_saving() {
299 self.daylight_saving_offset
300 } else {
301 self.standard_offset
302 },
303 ];
304 for offset in offsets {
305 // A candidate outside the i64 range cannot be represented.
306 let Some(utc) = local_seconds.checked_sub(i64::from(offset)) else {
307 continue;
308 };
309 // The candidate is valid when the zone really uses this offset at
310 // that instant.
311 if self.offset_at(utc) == offset && !found[..count].contains(&utc) {
312 found[count] = utc;
313 count += 1;
314 }
315 }
316 match count {
317 0 => LocalToUtc::Nonexistent,
318 1 => LocalToUtc::Unique(found[0]),
319 _ => LocalToUtc::Ambiguous {
320 earlier: found[0].min(found[1]),
321 later: found[0].max(found[1]),
322 },
323 }
324 }
325}
326
327/// The result of converting a UTC instant to local time.
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329pub struct Local<'a> {
330 /// The local date and time.
331 pub date_time: DateTime,
332 /// The offset in seconds east of UTC at that instant.
333 pub offset_seconds: i32,
334 /// The zone abbreviation at that instant, for example `CEST`.
335 pub abbreviation: &'a str,
336 /// Whether daylight saving time applies.
337 pub daylight_saving: bool,
338}
339
340/// The result of converting a local date and time to UTC.
341#[derive(Clone, Copy, Debug, PartialEq, Eq)]
342pub enum LocalToUtc {
343 /// The local time maps to exactly one UTC instant, in seconds since the
344 /// Unix epoch.
345 Unique(i64),
346 /// The local time happens twice, because the clocks were set back. `earlier`
347 /// and `later` are the two UTC instants in seconds since the Unix epoch;
348 /// `earlier` is the one with the larger offset east of UTC.
349 Ambiguous {
350 /// The first of the two instants.
351 earlier: i64,
352 /// The second of the two instants.
353 later: i64,
354 },
355 /// The local time never happens, because the clocks were set forward, or
356 /// because no UTC instant in the `i64` second range can represent it.
357 Nonexistent,
358}
359
360impl LocalToUtc {
361 /// Whether the local time maps to exactly one instant.
362 pub fn is_unique(&self) -> bool {
363 matches!(self, LocalToUtc::Unique(_))
364 }
365
366 /// Whether the local time happens twice.
367 pub fn is_ambiguous(&self) -> bool {
368 matches!(self, LocalToUtc::Ambiguous { .. })
369 }
370
371 /// Whether the local time never happens.
372 pub fn is_nonexistent(&self) -> bool {
373 matches!(self, LocalToUtc::Nonexistent)
374 }
375
376 /// The earliest UTC instant that matches the local time, in seconds since
377 /// the Unix epoch. None when the local time never happens.
378 pub fn earliest(&self) -> Option<i64> {
379 match self {
380 LocalToUtc::Unique(utc) => Some(*utc),
381 LocalToUtc::Ambiguous { earlier, .. } => Some(*earlier),
382 LocalToUtc::Nonexistent => None,
383 }
384 }
385}