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