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