Skip to main content

satellite_datetime/earth/
mod.rs

1//! Earth civil time: leap seconds, Gregorian, ISO 8601, POSIX Unix, DUT1, ERA.
2//!
3//! **Layers.** Core [`crate::Instant`] stays on TAI nanoseconds. This module is a
4//! *projection* of that instant.
5//!
6//! - **Convenience:** [`Instant::to_utc`], [`dut1`], [`Instant::earth_rotation_angle_rad`]
7//!   reconstruct civil UTC (search loop). Fine for logs and one-off conversions.
8//! - **Hot path:** pin a [`UtcDay`] (or keep a [`CivilUtc`]) and call
9//!   [`UtcDay::civil_from_instant`], [`dut1_at`], [`era_at_utc`]. No `to_utc` search.
10//! - **Streaming:** [`UtcContext`] re-pins the day when a sample crosses midnight.
11
12mod iso8601;
13mod leap;
14mod unix;
15mod ut1;
16mod ut1_table;
17mod utc_day;
18
19pub use iso8601::{format_rfc3339, parse_rfc3339};
20pub use leap::{leap_seconds_on_utc_day, tai_minus_utc, LeapInfo};
21pub use unix::{from_posix_nanos, from_posix_seconds, si_nanos_since_unix_epoch, to_posix_seconds};
22pub use ut1::{
23    dut1, dut1_at, era_at_utc, gmst_mean_at_utc, julian_ut1_at, utc_mjd, Ut1Info, UT1_TABLE_VERSION,
24};
25pub use utc_day::{UtcContext, UtcDay};
26
27use crate::constants::{NS_PER_DAY, NS_PER_SEC, TAI_EPOCH_UNIX_DAYS};
28use crate::duration::Duration;
29use crate::error::{Error, Result};
30use crate::instant::Instant;
31use crate::julian::{civil_from_unix_days, unix_days_from_civil};
32
33/// Proleptic Gregorian civil date and clock, tagged as UTC (may include second=60).
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub struct CivilUtc {
36    /// Proleptic Gregorian year.
37    pub year: i32,
38    /// Month `1..=12`.
39    pub month: u8,
40    /// Day of month, `1..=31` (validated).
41    pub day: u8,
42    /// Hour `0..=23`.
43    pub hour: u8,
44    /// Minute `0..=59`.
45    pub minute: u8,
46    /// Second `0..=60` (`60` only on a positive UTC leap second).
47    pub second: u8,
48    /// Nanosecond `0..=999_999_999`.
49    pub nanosecond: u32,
50}
51
52impl CivilUtc {
53    /// Validate ranges. `second` may be 60 (leap). Month 1–12, etc.
54    pub fn new(
55        year: i32,
56        month: u8,
57        day: u8,
58        hour: u8,
59        minute: u8,
60        second: u8,
61        nanosecond: u32,
62    ) -> Result<Self> {
63        if !(1..=12).contains(&month)
64            || hour > 23
65            || minute > 59
66            || second > 60
67            || nanosecond > 999_999_999
68        {
69            return Err(Error::InvalidTime);
70        }
71        if second == 60 && (hour != 23 || minute != 59) {
72            return Err(Error::InvalidTime);
73        }
74        let dim = days_in_month(year, month)?;
75        if day < 1 || day > dim {
76            return Err(Error::InvalidDate);
77        }
78        Ok(Self {
79            year,
80            month,
81            day,
82            hour,
83            minute,
84            second,
85            nanosecond,
86        })
87    }
88
89    /// Convert this UTC civil time to a TAI instant using the pinned leap table.
90    pub fn to_instant(self) -> Result<Instant> {
91        if self.year < 1960 {
92            return Err(Error::UtcUndefined);
93        }
94        let leap = tai_minus_utc(self.year, self.month, self.day, self.fraction_of_day())?;
95        if self.second == 60 && leap.leap_at_end != 1 {
96            return Err(Error::InvalidTime);
97        }
98        let unix_days = unix_days_from_civil(self.year, self.month, self.day);
99        let days_from_tai_epoch = (unix_days - TAI_EPOCH_UNIX_DAYS) as i128;
100        let mut sod_ns = (self.hour as i128) * 3600 * NS_PER_SEC
101            + (self.minute as i128) * 60 * NS_PER_SEC
102            + (self.second as i128) * NS_PER_SEC
103            + self.nanosecond as i128;
104        if self.second == 60 {
105            // 23:59:60 is the 86400th second of a leap day (0-based sod = 86400).
106            sod_ns = 86_400 * NS_PER_SEC + self.nanosecond as i128;
107        }
108        let dat_ns = Duration::from_seconds_f64(leap.tai_minus_utc)?.as_nanos();
109        let tai_ns = days_from_tai_epoch
110            .checked_mul(NS_PER_DAY)
111            .and_then(|d| d.checked_add(sod_ns))
112            .and_then(|d| d.checked_add(dat_ns))
113            .ok_or(Error::Overflow)?;
114        Ok(Instant::from_tai_nanos(tai_ns))
115    }
116
117    fn fraction_of_day(self) -> f64 {
118        let s = self.hour as f64 * 3600.0
119            + self.minute as f64 * 60.0
120            + self.second.min(59) as f64
121            + self.nanosecond as f64 / 1e9;
122        s / 86_400.0
123    }
124}
125
126impl Instant {
127    /// UTC civil time. `second` may be 60 on a leap-second day.
128    ///
129    /// Convenience inverse: searches nearby UTC days using the leap table.
130    /// For many instants on one date, pin [`crate::UtcDay`] once and call
131    /// [`crate::UtcDay::civil_from_instant`].
132    pub fn to_utc(self) -> Result<CivilUtc> {
133        let tai_ns = self.as_tai_nanos();
134        let approx = tai_ns.saturating_sub(37 * NS_PER_SEC);
135        let mut day_index = approx / NS_PER_DAY;
136        let sod0 = approx % NS_PER_DAY;
137        if sod0 < 0 {
138            day_index -= 1;
139        }
140        let unix0 = day_index as i64 + TAI_EPOCH_UNIX_DAYS;
141        for delta in [-2, -1, 0, 1, 2] {
142            let unix_days = unix0 + delta;
143            let (y, m, d) = civil_from_unix_days(unix_days);
144            if y < 1960 {
145                continue;
146            }
147            let leap = match tai_minus_utc(y, m, d, 0.0) {
148                Ok(l) => l,
149                Err(Error::LeapTableExpired) => continue,
150                Err(e) => return Err(e),
151            };
152            let dat_ns = Duration::from_seconds_f64(leap.tai_minus_utc)?.as_nanos();
153            let idx = (unix_days - TAI_EPOCH_UNIX_DAYS) as i128;
154            let midnight_tai = idx
155                .checked_mul(NS_PER_DAY)
156                .and_then(|v| v.checked_add(dat_ns))
157                .ok_or(Error::Overflow)?;
158            let since = tai_ns.checked_sub(midnight_tai).ok_or(Error::Overflow)?;
159            let day_len = NS_PER_DAY + i128::from(leap.leap_at_end) * NS_PER_SEC;
160            if since >= 0 && since < day_len {
161                match civil_from_since(y, m, d, since, leap.leap_at_end) {
162                    Ok(c) => return Ok(c),
163                    Err(Error::InvalidTime) => continue,
164                    Err(e) => return Err(e),
165                }
166            }
167        }
168        Err(Error::UtcUndefined)
169    }
170}
171
172pub(crate) fn civil_from_since(
173    y: i32,
174    m: u8,
175    d: u8,
176    since: i128,
177    leap_at_end: i8,
178) -> Result<CivilUtc> {
179    if leap_at_end == 1 && since >= NS_PER_DAY {
180        let nano = (since - NS_PER_DAY) as u32;
181        return Ok(CivilUtc {
182            year: y,
183            month: m,
184            day: d,
185            hour: 23,
186            minute: 59,
187            second: 60,
188            nanosecond: nano,
189        });
190    }
191    let hour = (since / (3600 * NS_PER_SEC)) as u8;
192    let rem = since % (3600 * NS_PER_SEC);
193    let minute = (rem / (60 * NS_PER_SEC)) as u8;
194    let rem = rem % (60 * NS_PER_SEC);
195    let second = (rem / NS_PER_SEC) as u8;
196    let nanosecond = (rem % NS_PER_SEC) as u32;
197    CivilUtc::new(y, m, d, hour, minute, second, nanosecond)
198}
199
200pub(crate) fn days_in_month(year: i32, month: u8) -> Result<u8> {
201    match month {
202        1 | 3 | 5 | 7 | 8 | 10 | 12 => Ok(31),
203        4 | 6 | 9 | 11 => Ok(30),
204        2 => Ok(if is_leap_year(year) { 29 } else { 28 }),
205        _ => Err(Error::InvalidDate),
206    }
207}
208
209pub(crate) const fn is_leap_year(year: i32) -> bool {
210    let y = year;
211    (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn erfa_utc_to_tt_example() {
220        // SOFA cookbook: 2010-07-24 11:18:07.318 UTC → 11:19:13.502 TT
221        let c = CivilUtc::new(2010, 7, 24, 11, 18, 7, 318_000_000).unwrap();
222        let inst = c.to_instant().unwrap();
223        let tt_ns = inst.reading_tt().as_nanos();
224        let tai_days = (unix_days_from_civil(2010, 7, 24) - TAI_EPOCH_UNIX_DAYS) as i128;
225        let expected_tt =
226            tai_days * NS_PER_DAY + ((11 * 3600 + 19 * 60 + 13) as i128) * NS_PER_SEC + 502_000_000;
227        assert_eq!(tt_ns, expected_tt);
228    }
229
230    #[test]
231    fn leap_second_2016() {
232        let leap = CivilUtc::new(2016, 12, 31, 23, 59, 60, 0).unwrap();
233        let inst = leap.to_instant().unwrap();
234        let next = CivilUtc::new(2017, 1, 1, 0, 0, 0, 0)
235            .unwrap()
236            .to_instant()
237            .unwrap();
238        assert_eq!(next.duration_since(inst).unwrap(), Duration::SECOND);
239        let back = inst.to_utc().unwrap();
240        assert_eq!(back.second, 60);
241        assert_eq!(back.year, 2016);
242        assert_eq!(back.month, 12);
243        assert_eq!(back.day, 31);
244    }
245
246    #[test]
247    fn after_leap() {
248        let c = CivilUtc::new(2017, 1, 1, 0, 0, 0, 0).unwrap();
249        let inst = c.to_instant().unwrap();
250        let back = inst.to_utc().unwrap();
251        assert_eq!(back, c);
252        let leap = tai_minus_utc(2017, 1, 1, 0.0).unwrap();
253        assert_eq!(leap.tai_minus_utc, 37.0);
254    }
255}