Skip to main content

deep_time/dt/
conversions.rs

1use crate::historical_utc::historical_utc_offset;
2use crate::{
3    Drift, Dt, LB_DEN, LB_NUM, LG_DEN, LG_NUM, Scale, TCG_TCB_REF_ATTOS_SINCE_J2000, TDB0_ATTOS,
4    TT_TAI_OFFSET,
5};
6
7impl Dt {
8    /// Converts this instant to its internally stored `target` scale and returns
9    /// the signed difference from the given epoch.
10    ///
11    /// This is a low-level `const fn` used internally by higher-level conversion
12    /// methods such as [`to_ymd`](Dt::to_ymd).
13    ///
14    /// ## Arguments
15    ///
16    /// - `epoch` — The reference epoch (e.g. [`Dt::UNIX_EPOCH`]) from which the
17    ///   difference is calculated.
18    /// - `convert_epoch` — Whether to also convert the provided `epoch` to this
19    ///   [`Dt`]'s `target` time scale.
20    ///
21    /// ## Returns
22    ///
23    /// A [`Dt`] representing the signed difference (seconds + attoseconds) between
24    /// this instant (after conversion to `to`) and the provided `epoch`.
25    ///
26    /// It can be interpreted as a timestamp when `epoch` is something like
27    /// [`Dt::UNIX_EPOCH`](../struct.Dt.html#associatedconstant.UNIX_EPOCH) (e.g. for
28    /// generating Unix timestamps via `.to_ms()` or `.to_sec()`).
29    ///
30    /// ## See also
31    ///
32    /// * [`Dt::to`](../struct.Dt.html#method.to).
33    /// * [`Dt::to_diff_raw`](../struct.Dt.html#method.to_diff_raw).
34    /// * [`Dt::from_diff_and_scale`](../struct.Dt.html#method.from_diff_and_scale).
35    ///
36    /// ## Examples
37    ///
38    /// ```rust
39    /// use deep_time::{Dt, Scale};
40    ///
41    /// let dt = Dt::from_ymd(2024, 6, 15, Scale::UTC, 12, 0, 0, 0);
42    /// let diff = dt.to_scale_and_diff(Dt::UNIX_EPOCH, true);
43    ///
44    /// // diff can be used as a Unix timestamp offset
45    /// let unix_ms = diff.to_ms();
46    /// assert!(unix_ms > 1_700_000_000_000);
47    /// ```
48    pub const fn to_scale_and_diff(&self, epoch: Dt, convert_epoch: bool) -> Dt {
49        if convert_epoch {
50            self.to(self.target).to_diff_raw(epoch.to(self.target))
51        } else {
52            self.to(self.target).to_diff_raw(epoch)
53        }
54    }
55
56    /// Creates a **TAI** [`Dt`] by adding a difference to an epoch and interpreting
57    /// the result on the given time scale.
58    ///
59    /// This is the inverse counterpart to
60    /// [`Dt::to_scale_and_diff`](../struct.Dt.html#method.to_scale_and_diff)
61    /// and is used by [`Dt::from_ymd`](../struct.Dt.html#method.from_ymd)
62    /// and related constructors.
63    ///
64    /// ## Arguments
65    ///
66    /// - `diff` — The signed difference (as a [`Dt`]) to add to the epoch.
67    /// - `epoch` — The reference epoch (commonly
68    ///   [`Dt::UNIX_EPOCH`](../struct.Dt.html#associatedconstant.UNIX_EPOCH) or
69    ///   [`Dt::ZERO`](../struct.Dt.html#associatedconstant.ZERO)).
70    /// - `current` — The time scale on which `diff` + `epoch` should be interpreted.
71    ///
72    /// ## Returns
73    ///
74    /// A [`Dt`] on the **TAI** scale representing the absolute instant
75    /// `epoch + diff` when interpreted on `current`.
76    ///
77    /// ## Notes
78    ///
79    /// - The input `diff` is treated as being on the `current` scale.
80    /// - The final result is always converted to TAI (the internal canonical representation).
81    ///
82    /// ## See also
83    ///
84    /// - [`Dt::to_scale_and_diff`](../struct.Dt.html#method.to_scale_and_diff)
85    /// - [`Dt::from_attos`](../struct.Dt.html#method.from_attos)
86    ///
87    /// ## Examples
88    ///
89    /// ```rust
90    /// use deep_time::{Dt, Scale};
91    ///
92    /// let diff = Dt::from_tai_sec(1_718_467_200); // ~2024-06-15
93    /// let dt = Dt::from_diff_and_scale(diff, Dt::UNIX_EPOCH, true);
94    ///
95    /// let ymd = dt.to_ymd();
96    /// assert_eq!(ymd.yr(), 2024);
97    /// assert_eq!(ymd.mo(), 6);
98    /// assert_eq!(ymd.day(), 15);
99    /// ```
100    pub const fn from_diff_and_scale(diff: Dt, epoch: Dt, convert_epoch: bool) -> Dt {
101        if convert_epoch {
102            Self::from_attos_with_target(
103                epoch
104                    .to(diff.scale)
105                    .to_attos()
106                    .saturating_add(diff.to_attos()),
107                diff.scale,
108                diff.target,
109            )
110        } else {
111            Self::from_attos_with_target(
112                epoch.to_attos().saturating_add(diff.to_attos()),
113                diff.scale,
114                diff.target,
115            )
116        }
117    }
118
119    /// Converts the internal attos to be on the TAI time [`Scale`].
120    ///
121    /// ```rust
122    /// use deep_time::{Dt, Scale};
123    ///
124    /// let tai = Dt::from_ymd(2000, 1, 1, Scale::UTC, 12, 0, 0, 0);
125    /// let tt = tai.to(Scale::TT);
126    ///
127    /// assert_eq!(tt.scale, Scale::TT);
128    ///
129    /// let roundtrip = tt.to_tai();
130    ///
131    /// assert_eq!(tai.scale, Scale::TAI);
132    /// assert_eq!(roundtrip, tai);
133    /// ```
134    ///
135    /// See [`Dt::to`](../struct.Dt.html#method.to) for more info.
136    pub const fn to_tai(&self) -> Dt {
137        match self.scale {
138            // we're going utc -> tai, check if it's
139            // post 1972 using the leap seconds table
140            Scale::UTC | Scale::UtcHist | Scale::UtcSpice => match self.utc_to_tai() {
141                // leap seconds table returned an offset, so use that
142                Some(dt) => dt.with(Scale::TAI),
143                // leap seconds table returned None so it must be pre 1972
144                None => match self.scale {
145                    Scale::UtcHist => match historical_utc_offset(self) {
146                        Some(offset) => self.add(Dt::span_f(offset)).with(Scale::TAI),
147                        None => self.with(Scale::TAI),
148                    },
149                    Scale::UtcSpice => self.add_sec(9).with(Scale::TAI),
150                    _ => self.with(Scale::TAI),
151                },
152            },
153            Scale::TAI => *self,
154            Scale::TT => Dt::new(
155                self.attos.saturating_sub(TT_TAI_OFFSET.to_attos()),
156                Scale::TAI,
157                self.target,
158            ),
159            Scale::GPS | Scale::QZSS | Scale::GST => Dt::new(
160                self.attos.saturating_add(Dt::SEC_19.to_attos()),
161                Scale::TAI,
162                self.target,
163            ),
164            Scale::BDT => Dt::new(
165                self.attos.saturating_add(Dt::SEC_33.to_attos()),
166                Scale::TAI,
167                self.target,
168            ),
169            Scale::TDB | Scale::ET => {
170                Self::tdb_to_tai(Dt::new(self.attos, Scale::TAI, self.target))
171            }
172            Scale::TCG => {
173                let tt = Self::tcg_to_tt(Dt::new(self.attos, Scale::TAI, self.target));
174                tt.sub(TT_TAI_OFFSET)
175            }
176            Scale::TCB => {
177                let tdb = Self::tcb_to_tdb(Dt::new(self.attos, Scale::TAI, self.target));
178                Self::tdb_to_tai(tdb)
179            }
180            Scale::LTC => {
181                let tt = Self::ltc_to_tt(Dt::new(self.attos, Scale::TAI, self.target));
182                tt.sub(TT_TAI_OFFSET)
183            }
184            Scale::TCL => Self::tcl_to_tai(Dt::new(self.attos, Scale::TAI, self.target)),
185            _ => Dt::new(self.attos, Scale::TAI, self.target),
186        }
187    }
188
189    /// Converts directly to `new` [`Scale`], without first converting to TAI.
190    ///
191    /// **Warning:**
192    ///
193    /// - This function should really only be used if the [`Dt`] is on the TAI
194    ///   time scale, or if you really know what you're doing.
195    /// - For the normal time scale conversion function see
196    ///   [`Dt::to`](../struct.Dt.html#method.to) which first converts
197    ///   to TAI before converting to the target scale.
198    pub const fn convert(&self, new: Scale) -> Dt {
199        match new {
200            Scale::TAI => self.to_tai(),
201            Scale::UTC | Scale::UtcHist | Scale::UtcSpice => match self.tai_to_utc() {
202                // leap seconds table returned an offset, so use that
203                Some(dt) => dt.with(new),
204                // leap seconds table returned None so it must be pre 1972
205                None => match self.scale {
206                    Scale::UtcHist => match historical_utc_offset(self) {
207                        Some(offset) => self.sub(Dt::span_f(offset)).with(new),
208                        None => self.with(new),
209                    },
210                    Scale::UtcSpice => self.add_sec(-9).with(new),
211                    _ => self.with(new),
212                },
213            },
214            Scale::TT => self.add(TT_TAI_OFFSET).with(new),
215            Scale::GPS | Scale::QZSS | Scale::GST => {
216                self.add_attos(-Dt::SEC_19.to_attos()).with(new)
217            }
218            Scale::BDT => self.add_attos(-Dt::SEC_33.to_attos()).with(new),
219            Scale::TDB | Scale::ET => Self::tai_to_tdb(*self).with(new),
220            Scale::TCG => Self::tai_to_tcg(*self).with(new),
221            Scale::TCB => Self::tai_to_tcb(*self).with(new),
222            Scale::LTC => {
223                let tt = self.add(TT_TAI_OFFSET);
224                Self::tt_to_ltc(tt).with(new)
225            }
226            Scale::TCL => Self::tai_to_tcl(*self).with(new),
227            _ => *self,
228        }
229    }
230
231    /// Converts this instant to another time scale, going via TAI.
232    ///
233    /// Essentially when converting TT to TDB the internal process goes like TT
234    /// -> TAI -> TDB. It uses the [`Dt`]s `scale` field to determine what scale
235    /// to convert from to TAI, and then the `new` arg dictates the new time scale.
236    ///
237    /// - Assumes that this [`Dt`] is measuring time since **2000-01-01 12:00:00**.
238    /// - It is not necessary to do this if you just want to use such functions
239    ///   as [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd) as these internally
240    ///   convert to the scale of the object's `target` field before output.
241    /// - If a TAI [`Dt`] was created using
242    ///   [`Dt::from_ymd`](../struct.Dt.html#method.from_ymd) and the datetime
243    ///   had 60 seconds, converting to UTC would lose that info. To round trip a
244    ///   60 second UTC datetime you need only set the
245    ///   [`Dt::target`](../struct.Dt.html#method.target) [`Scale`] to `UTC` and
246    ///   then call the desired output function, such as
247    ///   [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd).
248    /// - The internal `attos` field changes to be on the new time scale.
249    /// - The [`Dt`]s `target` field is ignored and left unchanged.
250    /// - The [`Dt`]s `scale` field is changed to the new [`Scale`].
251    ///
252    /// ## Returns
253    ///
254    /// - A [`Dt`] representing the same physical instant but on the `new` scale.
255    /// - The returned objects `scale` field has been changed to `new`.
256    ///
257    /// If `current == new`, this method returns `*self` without any computation.
258    ///
259    /// ## See also
260    ///
261    /// * [`Dt::to_tai`](../struct.Dt.html#method.to_tai)
262    /// * [`Dt::from_attos`](../struct.Dt.html#method.from_attos)
263    ///
264    /// ## Examples
265    ///
266    /// ```rust
267    /// use deep_time::{Dt, Scale};
268    ///
269    /// let tai = Dt::from_ymd(2024, 6, 15, Scale::UTC, 12, 0, 0, 0);
270    /// let tt = tai.to(Scale::TT);
271    /// let tdb = tt.to(Scale::TDB);
272    ///
273    /// // the objects have kept the scale they originally came
274    /// // from using their `target` field, which was UTC in the
275    /// // from_ymd function
276    /// assert_eq!(tdb.target, Scale::UTC);
277    ///
278    /// let roundtrip = tdb.to(Scale::TAI);
279    ///
280    /// let ymd = roundtrip.to_ymd();
281    ///
282    /// assert_eq!(ymd.yr(), 2024);
283    /// assert_eq!(ymd.mo(), 6);
284    /// assert_eq!(ymd.day(), 15);
285    /// assert_eq!(ymd.hr(), 12);
286    /// assert_eq!(ymd.min(), 0);
287    /// assert_eq!(ymd.sec(), 0);
288    /// assert_eq!(ymd.attos(), 0);
289    /// ```
290    #[inline]
291    pub const fn to(&self, new: Scale) -> Dt {
292        if matches!(self.scale, Scale::TAI) {
293            self.convert(new)
294        } else if !self.scale.eq(new) {
295            self.to_tai().convert(new)
296        } else {
297            *self
298        }
299    }
300
301    #[inline(always)]
302    pub(crate) const fn utc_to_tai(&self) -> Option<Dt> {
303        match self.leap_sec(true) {
304            Some(info) => Some(self.add_sec(info.offset as i128)),
305            None => None,
306        }
307    }
308
309    #[inline(always)]
310    pub(crate) const fn tai_to_utc(&self) -> Option<Dt> {
311        match self.leap_sec(false) {
312            Some(info) => Some(self.add_sec(-info.offset as i128)),
313            None => None,
314        }
315    }
316
317    #[inline]
318    pub(crate) const fn tai_to_tcg(tai: Dt) -> Dt {
319        let tt = tai.add(TT_TAI_OFFSET);
320        Self::tt_to_tcg(tt)
321    }
322
323    #[inline]
324    pub(crate) const fn tai_to_tcb(tai: Dt) -> Dt {
325        let tdb = Self::tai_to_tdb(tai);
326        Self::tdb_to_tcb(tdb)
327    }
328
329    /// Exact integer helper: elapsed attoseconds since the TCG/TCB reference epoch (1977-01-01.0 TAI),
330    /// using only the numerical value of the supplied `Dt` (scale is ignored).
331    #[inline(always)]
332    pub(crate) const fn to_attos_since_tcg_tcb_epoch(numerical: Dt) -> i128 {
333        numerical.to_attos() - TCG_TCB_REF_ATTOS_SINCE_J2000
334    }
335
336    /// Exact fixed-point multiplication: `attos * num / den` (handles negative values safely,
337    /// no overflow for library time range).
338    pub(crate) const fn mul_rate(attos: i128, num: i128, den: i128) -> i128 {
339        if attos == 0 {
340            return 0;
341        }
342        let sign = if attos < 0 { -1i128 } else { 1i128 };
343        let a = if attos < 0 { -attos } else { attos };
344        let q = a / den;
345        let r = a % den;
346        sign * (q * num + (r * num) / den)
347    }
348
349    #[inline(always)]
350    pub(crate) const fn mul_lg(attos: i128) -> i128 {
351        Self::mul_rate(attos, LG_NUM, LG_DEN)
352    }
353
354    #[inline(always)]
355    pub(crate) const fn mul_lb(attos: i128) -> i128 {
356        Self::mul_rate(attos, LB_NUM, LB_DEN)
357    }
358
359    pub(crate) const fn tt_to_tcg(tt: Dt) -> Dt {
360        let elapsed = Self::to_attos_since_tcg_tcb_epoch(tt);
361        let span_attos = Self::mul_lg(elapsed);
362        tt.add_attos(span_attos)
363    }
364
365    pub(crate) const fn tcg_to_tt(tcg: Dt) -> Dt {
366        let elapsed_cg = Self::to_attos_since_tcg_tcb_epoch(tcg);
367        let span_attos = Self::mul_rate(elapsed_cg, LG_NUM, LG_DEN + LG_NUM);
368        tcg.add_attos(-span_attos)
369    }
370
371    pub(crate) const fn tcb_to_tdb(tcb: Dt) -> Dt {
372        let elapsed_cg = Self::to_attos_since_tcg_tcb_epoch(tcb);
373        let span_attos = Self::mul_rate(elapsed_cg, LB_NUM, LB_DEN + LB_NUM);
374        tcb.add_attos(-span_attos).add_attos(-TDB0_ATTOS)
375    }
376
377    pub(crate) const fn tdb_to_tcb(tdb: Dt) -> Dt {
378        let elapsed = Self::to_attos_since_tcg_tcb_epoch(tdb);
379        let span_attos = Self::mul_lb(elapsed);
380        tdb.add_attos(span_attos).add_attos(TDB0_ATTOS)
381    }
382
383    /// Converts this instant to any other [`Scale`] while applying an exact quadratic relativistic
384    /// or clock-drift correction defined by a [`Drift`] model relative to a reference instant.
385    pub const fn convert_using_drift(self, reference: Dt, drift: Drift) -> Dt {
386        let span = self.to_diff_raw(reference);
387        let correction = drift.time_diff_after(&span);
388        self.add(correction)
389    }
390
391    /// Performs the inverse conversion of [`Dt::convert_using_drift`], recovering the original proper
392    /// time on the source clock scale.
393    ///
394    /// A fixed-point iteration (at most 16 steps) is used to solve the implicit equation. For the common
395    /// case of a pure constant offset the function returns immediately without iteration.
396    pub const fn convert_back_using_drift(self, reference: Dt, drift: Drift) -> Dt {
397        if drift.rate.is_zero() && drift.accel.is_zero() {
398            return self.sub(drift.constant);
399        }
400        let mut guess = self;
401        let mut i = 0u32;
402        while i < 16 {
403            let span = guess.to_diff_raw(reference);
404            let correction = drift.time_diff_after(&span);
405            guess = self.sub(correction);
406            i += 1;
407        }
408        guess
409    }
410}