Skip to main content

datetime/
lib.rs

1// datetime -- calendar time: timestamps, civil dates, RFC 3339, time zones, cron schedules
2//
3//   Timestamp { secs, nanos }          seconds since 1970-01-01 00:00 UTC
4//   Civil { year .. second, nanos }    a calendar date and wall time (no zone)
5//   days_from_civil / civil_from_days / days_in_month / is_leap / weekday (0 = Monday)
6//   iso_week / iso_weeks_in_year / iso_week_monday   ISO 8601 weeks (Monday to Sunday, week 1
7//                                      holds the year's first Thursday)
8//   rfc3339(ts) / rfc3339_offset(ts, offset) / parse_rfc3339(s)
9//   format_date_time(ts, &zone, en) / format_date / format_time / format_duration(secs, en)
10//   tz::Zone                           IANA zones with their current DST rule (zones.rs from
11//                                      tools/gen_tz.py), Windows zone keys, POSIX TZ strings;
12//                                      offset_at / to_local / from_local (Single, Ambiguous,
13//                                      Gap)
14//   cron::Cron                         5-field cron expressions: next_after in a zone (a time
15//                                      in a DST gap runs right after the gap, a repeated time
16//                                      runs once), next_n, describe (de / en)
17//
18// No clock here: plat::unix_time_ns gives "now"; datetime only computes.
19#![no_std]
20#![forbid(unsafe_code)]
21
22extern crate alloc;
23
24pub mod cron;
25pub mod tz;
26mod zones;
27
28use alloc::format;
29use alloc::string::String;
30
31pub use cron::{Cron, CronError};
32pub use tz::{LocalResult, Zone};
33
34/// a point in time: seconds since 1970-01-01 00:00:00 UTC and nanoseconds
35#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
36pub struct Timestamp {
37    pub secs: i64,
38    pub nanos: u32,
39}
40
41impl Timestamp {
42    pub const fn from_secs(secs: i64) -> Timestamp {
43        Timestamp { secs, nanos: 0 }
44    }
45    /// from nanoseconds since the epoch (plat::unix_time_ns)
46    pub const fn from_nanos(ns: i64) -> Timestamp {
47        Timestamp { secs: ns.div_euclid(1_000_000_000), nanos: ns.rem_euclid(1_000_000_000) as u32 }
48    }
49    pub const fn from_millis(ms: i64) -> Timestamp {
50        Timestamp { secs: ms.div_euclid(1000), nanos: (ms.rem_euclid(1000) * 1_000_000) as u32 }
51    }
52    pub const fn as_millis(&self) -> i64 {
53        self.secs.saturating_mul(1000).saturating_add((self.nanos / 1_000_000) as i64)
54    }
55    pub const fn add_secs(&self, s: i64) -> Timestamp {
56        Timestamp { secs: self.secs.saturating_add(s), nanos: self.nanos }
57    }
58}
59
60/// a calendar date and wall time without a zone
61#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
62pub struct Civil {
63    pub year: i32,
64    pub month: u8,
65    pub day: u8,
66    pub hour: u8,
67    pub minute: u8,
68    pub second: u8,
69    pub nanos: u32,
70}
71
72impl Civil {
73    pub const fn new(year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> Civil {
74        Civil { year, month, day, hour, minute, second, nanos: 0 }
75    }
76    pub const fn date(year: i32, month: u8, day: u8) -> Civil {
77        Civil::new(year, month, day, 0, 0, 0)
78    }
79    /// the civil time of seconds since the epoch read as UTC
80    pub fn from_unix(secs: i64) -> Civil {
81        let days = secs.div_euclid(86_400);
82        let rem = secs.rem_euclid(86_400);
83        let (y, m, d) = civil_from_days(days);
84        Civil::new(y, m, d, (rem / 3600) as u8, (rem % 3600 / 60) as u8, (rem % 60) as u8)
85    }
86    /// seconds since the epoch of this wall time read as UTC
87    pub fn to_unix(&self) -> i64 {
88        days_from_civil(self.year, self.month, self.day) * 86_400
89            + self.hour as i64 * 3600
90            + self.minute as i64 * 60
91            + self.second as i64
92    }
93    /// 0 = Monday .. 6 = Sunday
94    pub fn weekday(&self) -> u8 {
95        weekday(self.year, self.month, self.day)
96    }
97    pub fn is_valid(&self) -> bool {
98        (1..=12).contains(&self.month)
99            && self.day >= 1
100            && self.day <= days_in_month(self.year, self.month)
101            && self.hour < 24
102            && self.minute < 60
103            && self.second < 61
104    }
105    /// the same wall time `days` days later
106    pub fn add_days(&self, days: i64) -> Civil {
107        let (y, m, d) = civil_from_days(days_from_civil(self.year, self.month, self.day) + days);
108        Civil { year: y, month: m, day: d, ..*self }
109    }
110}
111
112pub fn is_leap(y: i32) -> bool {
113    (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
114}
115
116/// days of month m (1..12)
117pub fn days_in_month(y: i32, m: u8) -> u8 {
118    match m {
119        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
120        4 | 6 | 9 | 11 => 30,
121        2 if is_leap(y) => 29,
122        2 => 28,
123        _ => 0,
124    }
125}
126
127/// days since 1970-01-01 of a date (proleptic Gregorian; Howard Hinnant's algorithm)
128pub fn days_from_civil(y: i32, m: u8, d: u8) -> i64 {
129    let y = if m <= 2 { y as i64 - 1 } else { y as i64 };
130    let era = y.div_euclid(400);
131    let yoe = y - era * 400;
132    let mp = (m as i64 + 9) % 12;
133    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
134    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
135    era * 146_097 + doe - 719_468
136}
137
138/// (year, month, day) of days since 1970-01-01
139pub fn civil_from_days(z: i64) -> (i32, u8, u8) {
140    let z = z + 719_468;
141    let era = z.div_euclid(146_097);
142    let doe = z - era * 146_097;
143    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
144    let y = yoe + era * 400;
145    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
146    let mp = (5 * doy + 2) / 153;
147    let d = (doy - (153 * mp + 2) / 5 + 1) as u8;
148    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u8;
149    ((if m <= 2 { y + 1 } else { y }) as i32, m, d)
150}
151
152/// weekday of a date: 0 = Monday .. 6 = Sunday
153pub fn weekday(y: i32, m: u8, d: u8) -> u8 {
154    (days_from_civil(y, m, d) + 3).rem_euclid(7) as u8
155}
156
157/// the ISO 8601 weeks of week-numbering year y: 53 when the year starts on a Thursday, or on a
158/// Wednesday in a leap year, else 52
159pub fn iso_weeks_in_year(y: i32) -> u8 {
160    let jan1 = weekday(y, 1, 1);
161    if jan1 == 3 || (jan1 == 2 && is_leap(y)) { 53 } else { 52 }
162}
163
164/// the ISO 8601 week of a date -> (its week-numbering year, the week 1 ..= 53): the days of
165/// 29 December to 3 January may lie in the week of the other year (2026-12-31 is 2026-W53,
166/// 2027-01-01 too)
167pub fn iso_week(y: i32, m: u8, d: u8) -> (i32, u8) {
168    // the week's Thursday decides its year
169    let thu = days_from_civil(y, m, d) - weekday(y, m, d) as i64 + 3;
170    let (ty, _, _) = civil_from_days(thu);
171    (ty, ((thu - days_from_civil(ty, 1, 1)) / 7 + 1) as u8)
172}
173
174/// the Monday of ISO 8601 week `week` of week-numbering year y -> (year, month, day); a week
175/// beyond the year's last counts on into the next year
176pub fn iso_week_monday(y: i32, week: u8) -> (i32, u8, u8) {
177    // week 1 holds 4 January
178    let jan4 = days_from_civil(y, 1, 4);
179    civil_from_days(jan4 - weekday(y, 1, 4) as i64 + (week as i64 - 1) * 7)
180}
181
182fn two(s: &[u8], i: usize) -> Option<u32> {
183    let a = s.get(i)?.wrapping_sub(b'0');
184    let b = s.get(i + 1)?.wrapping_sub(b'0');
185    if a > 9 || b > 9 {
186        return None;
187    }
188    Some(a as u32 * 10 + b as u32)
189}
190
191/// "2026-10-12T19:58:00Z" (with ".123" milliseconds when the timestamp has them)
192pub fn rfc3339(ts: Timestamp) -> String {
193    rfc3339_offset(ts, 0)
194}
195
196/// the timestamp as local time with its UTC offset: "2026-10-12T21:58:00+02:00"
197pub fn rfc3339_offset(ts: Timestamp, offset_secs: i32) -> String {
198    // years 0000..9999 only: anything beyond is clamped
199    let lo = days_from_civil(0, 1, 1) * 86_400;
200    let hi = days_from_civil(9999, 12, 31) * 86_400 + 86_399;
201    let c = Civil::from_unix(ts.secs.saturating_add(offset_secs as i64).clamp(lo, hi));
202    let ms = ts.nanos / 1_000_000;
203    let frac = if ms != 0 { format!(".{:03}", ms) } else { String::new() };
204    let zone = if offset_secs == 0 {
205        String::from("Z")
206    } else {
207        let a = offset_secs.unsigned_abs();
208        format!("{}{:02}:{:02}", if offset_secs < 0 { '-' } else { '+' }, a / 3600, a % 3600 / 60)
209    };
210    format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}{}{}", c.year, c.month, c.day, c.hour, c.minute, c.second, frac, zone)
211}
212
213/// parse `YYYY-MM-DDTHH:MM:SS[.fff…](Z|±HH:MM)` (also with a space or lower-case t / z)
214pub fn parse_rfc3339(s: &str) -> Option<Timestamp> {
215    let b = s.trim().as_bytes();
216    if b.len() < 20 {
217        return None;
218    }
219    let y = two(b, 0)? * 100 + two(b, 2)?;
220    if b[4] != b'-' || b[7] != b'-' || !matches!(b[10], b'T' | b't' | b' ') || b[13] != b':' || b[16] != b':' {
221        return None;
222    }
223    let c = Civil::new(y as i32, two(b, 5)? as u8, two(b, 8)? as u8, two(b, 11)? as u8, two(b, 14)? as u8, two(b, 17)? as u8);
224    if !c.is_valid() {
225        return None;
226    }
227    let mut i = 19;
228    let mut nanos = 0u32;
229    if b.get(i) == Some(&b'.') {
230        i += 1;
231        let mut digits = 0;
232        while let Some(&d) = b.get(i) {
233            if !d.is_ascii_digit() {
234                break;
235            }
236            if digits < 9 {
237                nanos = nanos * 10 + (d - b'0') as u32;
238                digits += 1;
239            }
240            i += 1;
241        }
242        while digits < 9 {
243            nanos *= 10;
244            digits += 1;
245        }
246    }
247    let off = match b.get(i)? {
248        b'Z' | b'z' => {
249            i += 1;
250            0
251        }
252        &sign @ (b'+' | b'-') => {
253            let h = two(b, i + 1)? as i64;
254            if b.get(i + 3) != Some(&b':') {
255                return None;
256            }
257            let m = two(b, i + 4)? as i64;
258            if h > 23 || m > 59 {
259                return None;
260            }
261            i += 6;
262            let o = h * 3600 + m * 60;
263            if sign == b'-' { -o } else { o }
264        }
265        _ => return None,
266    };
267    if i != b.len() {
268        return None;
269    }
270    Some(Timestamp { secs: c.to_unix() - off, nanos })
271}
272
273/// "12.10.2026 19:58" (de) / "2026-10-12 19:58" (en) in a zone
274pub fn format_date_time(ts: Timestamp, zone: &Zone, en: bool) -> String {
275    let c = zone.to_local(ts);
276    if en {
277        format!("{:04}-{:02}-{:02} {:02}:{:02}", c.year, c.month, c.day, c.hour, c.minute)
278    } else {
279        format!("{:02}.{:02}.{:04} {:02}:{:02}", c.day, c.month, c.year, c.hour, c.minute)
280    }
281}
282
283/// "12.10.2026" / "2026-10-12"
284pub fn format_date(ts: Timestamp, zone: &Zone, en: bool) -> String {
285    let c = zone.to_local(ts);
286    if en {
287        format!("{:04}-{:02}-{:02}", c.year, c.month, c.day)
288    } else {
289        format!("{:02}.{:02}.{:04}", c.day, c.month, c.year)
290    }
291}
292
293/// "19:58"
294pub fn format_time(ts: Timestamp, zone: &Zone) -> String {
295    let c = zone.to_local(ts);
296    format!("{:02}:{:02}", c.hour, c.minute)
297}
298
299/// a duration for people: "42 s", "3 min 05 s", "1 h 12 min", "2 d 3 h"
300pub fn format_duration(secs: i64, en: bool) -> String {
301    let s = secs.max(0);
302    let d = if en { "d" } else { "T" };
303    if s < 60 {
304        format!("{} s", s)
305    } else if s < 3600 {
306        format!("{} min {:02} s", s / 60, s % 60)
307    } else if s < 86_400 {
308        format!("{} h {:02} min", s / 3600, s % 3600 / 60)
309    } else {
310        format!("{} {} {} h", s / 86_400, d, s % 86_400 / 3600)
311    }
312}
313
314/// a relative time for people: "vor 5 min" / "5 min ago", "in 2 h" (now and then in seconds)
315pub fn format_relative(now: i64, then: i64, en: bool) -> String {
316    let d = then - now;
317    let a = d.unsigned_abs() as i64;
318    let v = if a < 60 {
319        return String::from(if en { "just now" } else { "gerade eben" });
320    } else if a < 3600 {
321        format!("{} min", a / 60)
322    } else if a < 86_400 {
323        format!("{} h", a / 3600)
324    } else {
325        let n = a / 86_400;
326        // German: dative after "vor" / "in" ("vor 2 Tagen", "in 1 Tag")
327        format!("{} {}", n, match (en, n == 1) {
328            (true, true) => "day",
329            (true, false) => "days",
330            (false, true) => "Tag",
331            (false, false) => "Tagen",
332        })
333    };
334    match (d < 0, en) {
335        (true, true) => format!("{} ago", v),
336        (true, false) => format!("vor {}", v),
337        (false, true) => format!("in {}", v),
338        (false, false) => format!("in {}", v),
339    }
340}