Skip to main content

deep_time/dt/
mod.rs

1mod arithmetic;
2mod arithmetic_calendar;
3mod constructors;
4mod conveniences;
5mod et;
6mod from_ccsds;
7mod from_str;
8mod gregorian;
9mod helpers;
10mod julian_date;
11mod ops;
12mod to;
13mod to_bin_ccsds;
14mod to_scale;
15mod to_str;
16
17pub mod lunar;
18pub mod numbers_traits;
19
20#[cfg(feature = "alloc")]
21mod to_str_ccsds;
22
23#[cfg(feature = "hifitime")]
24mod hifitime;
25
26#[cfg(feature = "chrono")]
27mod chrono;
28
29#[cfg(feature = "jiff")]
30mod jiff;
31
32#[cfg(feature = "time")]
33mod time;
34
35#[cfg(feature = "mars")]
36pub mod mars;
37
38#[cfg(feature = "tdb-hi")]
39pub mod tdb_hi;
40
41#[cfg(not(feature = "tdb-hi"))]
42mod tdb;
43
44use crate::{ATTOS_PER_SEC, Scale};
45use core::fmt;
46
47/// **The library's central time type.** A high-precision instant/duration with attosecond
48/// resolution.
49///
50/// **Fields:**
51///
52/// - pub attos: [`i128`] - signed attosecond count. As a duration this is an
53///   elapsed span; as an instant it is an offset from some epoch (any epoch may
54///   apply depending on construction and use; calendar/conversion APIs commonly
55///   use the library epoch of 2000-01-01 noon).
56/// - pub scale: [`Scale`] - the current time scale of the object.
57/// - pub target: [`Scale`] - a target time scale used by many output functions such as
58///   [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd) and
59///   [`Dt::to_unix`](../struct.Dt.html#method.to_unix). The functions convert to the
60///   `target` time scale before producing an output.
61///
62/// **Notes:**
63///
64/// - In theory it supports a range of roughly ±5.39 trillion years but many of the to and
65///   from functions cap at i64 seconds, which can mean a range of ±292 billion years in practice.
66///   Additionally, when parsing dates with a timezone the Rust library `jiff` is used which has
67///   a limit of `-9999 - 9999` years.
68/// - Implements `Copy` and `Clone`. Optional derives for `serde` and `tsify` are available
69///   behind the corresponding features.
70/// - A wide range of math is available for this type, including basic calendar aware math and,
71///   with the `jiff-tz` feature enabled, timezone and DST aware math. **Behavior greatly
72///   differs between functions.**
73/// - **Comparison** (`==`, `Ord`, and [`Dt::cmp`](../struct.Dt.html#method.cmp)) uses only the
74///   `attos` field. `scale` and `target` are not consulted and no time-scale conversion is
75///   performed. To test whether two values denote the same physical instant, convert both to a
76///   common scale (e.g. with [`Dt::to`](../struct.Dt.html#method.to)) before comparing.
77///
78/// ```rust
79/// use deep_time::{Dt, Scale};
80///
81/// let tai = Dt::ZERO;
82/// let relabeled = tai.with(Scale::TT); // relabels scale only — attos unchanged
83///
84/// assert_eq!(tai, relabeled);
85/// assert_ne!(tai, tai.to(Scale::TT)); // .to() converts attos — no longer equal
86/// ```
87///
88/// ## Reference epoch and scales
89///
90/// - The librarys epoch for nearly all functionality such as the conversion functions is
91///   **2000-01-01 noon**. See also: [`Scale`](../enum.Scale.html).
92/// - Leap-second handling follows the chosen `Scale` (UTC, UtcSpice, UtcHist).
93///
94/// ## See also (non-exhaustive list)
95///
96/// ### From and to calendar dates
97///
98/// - [`Dt::from_ymd`](../struct.Dt.html#method.from_ymd)
99/// - [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd)
100///
101/// ### From and to str and bytes
102///
103/// Some of these require the alloc feature, they're marked with *
104///
105/// - [`Dt::from_str_parse`](../struct.Dt.html#method.from_str_parse)*
106/// - [`Dt::from_str_iso`](../struct.Dt.html#method.from_str_iso)
107/// - [`Dt::parse`](../struct.Dt.html#method.parse)
108/// - [`Dt::from_str`](../struct.Dt.html#method.from_str)
109/// - [`Dt::to_str`](../struct.Dt.html#method.to_str)*
110/// - [`Dt::to_str_in_offset`](../struct.Dt.html#method.to_str_in_offset)*
111/// - [`Dt::to_str_in_tz`](../struct.Dt.html#method.to_str_in_tz)*
112/// - [`Dt::to_str_iso8601`](../struct.Dt.html#method.to_str_iso8601)*
113/// - [`Dt::to_str_lite`](../struct.Dt.html#method.to_str_lite)
114/// - [`Dt::to_str_lite_in_offset`](../struct.Dt.html#method.to_str_lite_in_offset)
115/// - [`Dt::to_str_lite_in_tz`](../struct.Dt.html#method.to_str_lite_in_tz)
116///
117/// ### From and to julian dates
118///
119/// - [`Dt::from_jd_f`](../struct.Dt.html#method.from_jd_f)
120/// - [`Dt::from_mjd_f`](../struct.Dt.html#method.from_mjd_f)
121/// - [`Dt::to_jd_f`](../struct.Dt.html#method.to_jd_f)
122/// - [`Dt::to_mjd_f`](../struct.Dt.html#method.to_mjd_f)
123/// - [`Dt::ymd_to_jd`](../struct.Dt.html#method.ymd_to_jd)
124/// - [`Dt::jd_to_ymd`](../struct.Dt.html#method.jd_to_ymd)
125///
126/// ### Conversions, time scales etc.
127///
128/// - [`Dt::target`](../struct.Dt.html#method.target)
129/// - [`Dt::to`](../struct.Dt.html#method.to)
130/// - [`Dt::convert`](../struct.Dt.html#method.convert)
131/// - [`Dt::to_tai`](../struct.Dt.html#method.to_tai)
132/// - [`Dt::from_sec`](../struct.Dt.html#method.from_sec)
133/// - [`Dt::to_sec64_floor`](../struct.Dt.html#method.to_sec64_floor)
134/// - [`Dt::from_attos`](../struct.Dt.html#method.from_attos)
135/// - [`Dt::convert`](../struct.Dt.html#method.convert)
136/// - [`Dt::to_unix`](../struct.Dt.html#method.to_unix)
137/// - [`Dt::to_ntp`](../struct.Dt.html#method.to_ntp)
138/// - [`Dt::to_gps_wk_and_tow`](../struct.Dt.html#method.to_gps_wk_and_tow)
139///
140/// ### Conversions from and to types from other libraries
141///
142/// - [`Dt::to_hifitime_epoch`](../struct.Dt.html#method.to_hifitime_epoch)
143/// - [`Dt::to_jiff_timestamp`](../struct.Dt.html#method.to_jiff_timestamp)
144/// - [`Dt::to_chrono_datetime_utc`](../struct.Dt.html#method.to_chrono_datetime_utc)
145/// - [`Dt::to_time_timestamp`](../struct.Dt.html#method.to_time_timestamp)
146/// - [`Dt::from_hifitime_epoch`](../struct.Dt.html#method.from_hifitime_epoch)
147/// - [`Dt::from_jiff_timestamp`](../struct.Dt.html#method.from_jiff_timestamp)
148/// - [`Dt::from_chrono_datetime_utc`](../struct.Dt.html#method.from_chrono_datetime_utc)
149/// - [`Dt::from_time_timestamp`](../struct.Dt.html#method.from_time_timestamp)
150///
151/// ## Examples
152///
153/// ### Parsing a date
154///
155/// ```rust
156/// use deep_time::{Dt, Scale};
157///
158/// // uses impl FromStr but Dt::parse provides the same functionality
159/// let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
160///
161/// let ymd = x.to_ymd();
162/// assert_eq!(ymd.yr(), 2000);
163/// assert_eq!(ymd.mo(), 1);
164/// assert_eq!(ymd.day(), 1);
165/// assert_eq!(ymd.hr(), 12);
166/// assert_eq!(ymd.min(), 0);
167/// assert_eq!(ymd.sec(), 0);
168/// assert_eq!(ymd.attos(), 0);
169/// ```
170///
171/// ### Outputting a date to string / bytes
172///
173/// ```rust
174/// # #[cfg(all(any(feature = "jiff-tz", feature = "jiff-tz-bundle"), feature = "parse"))]
175/// # {
176/// use deep_time::{Dt, Lang, Scale};
177///
178/// let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
179///
180/// let s = x
181///  .to_str_in_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York", Lang::En)
182///  .unwrap();
183/// let b = x
184///  .to_str_lite_in_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York", Lang::En)
185///  .unwrap();
186///
187/// assert_eq!(s, "Saturday, January 01, 2000 07:00:00 America/New_York");
188/// assert_eq!(b.as_str(), "Saturday, January 01, 2000 07:00:00 America/New_York");
189/// # }
190/// ```
191///
192/// ### Creating a unix timestamp in milliseconds
193///
194/// ```rust
195/// use deep_time::{Dt, Scale};
196///
197/// // this fn converts from UTC and creates a TAI Dt
198/// let dt = Dt::from_ymd(2000, 1, 1, Scale::UTC, 12, 0, 0, 0);
199///
200/// // dt is internally TAI but has a UTC tag
201/// let unix_ms = dt.to_unix().to_ms().0;
202///
203/// // unix timestamp in ms for 2000-01-01 noon UTC
204/// assert_eq!(unix_ms, 946728000000);
205/// ```
206///
207/// ### Converting time scales
208///
209/// Many functions such as
210/// [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd) will convert to
211/// `TAI` from the [`Dt`]s current `scale` then to the [`Dt`]s `target`
212/// [`Scale`] prior to producing an output.
213///
214/// So you don't necessarily have to convert time scales prior to using
215/// many of the output functions. You just have to change the `target`
216/// time scale.
217///
218/// #### Using the target field
219///
220/// ```rust
221/// use deep_time::{Dt, Lang, Scale};
222///
223/// // Leap seconds were added to the seconds count
224/// // This Dt has attos that are now on the TAI timescale
225/// let dt = Dt::from_ymd(2025, 1, 1, Scale::UTC, 0, 0, 0, 0);
226///
227/// // The internal target is currently UTC so we don't need to do
228/// // anything to output back to UTC and round trip
229/// let bytes = dt.to_str_lite("%d %m %Y %H:%M:%S", Lang::En).unwrap();
230///
231/// assert_eq!(bytes.as_str(), "01 01 2025 00:00:00");
232///
233/// // Perhaps we want to make a GPS timestamp out of our Dt
234/// // If we want it to be on the GPS time scale we have to set the
235/// // target prior to calling to_gps()
236/// let gps = dt.target(Scale::GPS).to_gps().to_sec_f();
237/// ```
238///
239/// #### Converting the internal attos to a new time scale
240///
241/// ```rust
242/// use deep_time::{Dt, Scale};
243///
244/// // this fn converts from UTC and creates a TAI Dt
245/// let dt = Dt::from_ymd(2000, 1, 1, Scale::UTC, 12, 0, 0, 0);
246///
247/// // to tdb
248/// let tdb = dt.to(Scale::TDB);
249///
250/// // then to tt, the current scale is TDB
251/// let tt = tdb.to(Scale::TT);
252///
253/// // then back to TAI
254/// let tai = tt.to(Scale::TAI);
255///
256/// // round trip equality
257/// assert_eq!(dt, tai);
258/// ```
259///
260/// ### Performing some basic calendar aware math
261///
262/// ```rust
263/// use deep_time::{Dt, Scale};
264///
265/// let x = Dt::from_ymd(2000, 2, 29, Scale::UTC, 0, 0, 0, 0).to_ymd();
266/// let x = x.add_years(1);
267///
268/// assert_eq!(x.day(), 28);
269/// ```
270///
271/// ### Changing a dates format
272///
273/// ```rust
274/// use deep_time::{Dt, Lang, StrPTimeFmt};
275///
276/// let fmt = Dt::parse_fmt("%Y-%m-%dT%H:%M:%S").unwrap();
277///
278/// # #[cfg(feature = "alloc")]
279/// let s = fmt.to_str("2000-01-01T12:00:00", "%d %m %Y %H:%M:%S", false, false, false, Lang::En).unwrap();
280///
281/// # #[cfg(feature = "alloc")]
282/// assert_eq!(s, "01 01 2000 12:00:00", "expected: {}, got: {}", "01 01 2000 12:00:00", s);
283/// ```
284#[derive(Clone, Copy)]
285#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
286#[cfg_attr(feature = "tsify", derive(tsify::Tsify))]
287#[cfg_attr(feature = "defmt", derive(defmt::Format))]
288pub struct Dt {
289    /// Signed attosecond count.
290    ///
291    /// [`Dt`] can represent a duration or an instant. As a duration, `attos` is
292    /// simply an elapsed span. As an instant, it is an offset from some epoch —
293    /// any epoch may apply depending on how the value is constructed and used.
294    ///
295    /// Calendar and conversion APIs commonly interpret it relative to the library
296    /// epoch (2000-01-01 noon), but the field itself is only a count of attoseconds.
297    pub attos: i128,
298    /// The current time scale of this value.
299    pub scale: Scale,
300    /// Target time scale used by many output functions such as
301    /// [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd)
302    /// and
303    /// [`Dt::to_unix`](../struct.Dt.html#method.to_unix).
304    ///
305    /// These functions convert to this scale before producing output.
306    pub target: Scale,
307}
308
309impl Dt {
310    /// Returns a new [`Dt`] with the `target` field set to the given
311    /// `t` arg.
312    #[inline(always)]
313    pub const fn target(&self, t: Scale) -> Dt {
314        Dt::new(self.attos, self.scale, t)
315    }
316
317    /// Returns a new [`Dt`] with the `scale` field set to the given
318    /// `s` arg.
319    ///
320    /// **Does NOT perform any time scale conversions**.
321    #[inline(always)]
322    pub const fn with(&self, s: Scale) -> Dt {
323        Dt::new(self.attos, s, self.target)
324    }
325}
326
327impl Default for Dt {
328    fn default() -> Dt {
329        Self::ZERO
330    }
331}
332
333impl fmt::Display for Dt {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        let total = self.to_attos();
336        let precision = f.precision().unwrap_or(18).min(18);
337
338        let is_negative = total < 0;
339        let abs_attos = if is_negative {
340            total.wrapping_neg() as u128
341        } else {
342            total as u128
343        };
344
345        if is_negative {
346            f.write_str("-")?;
347        } else if f.sign_plus() {
348            f.write_str("+")?;
349        }
350
351        let attos_per_sec = ATTOS_PER_SEC as u128;
352        let whole_seconds = abs_attos / attos_per_sec;
353        let fractional_attos = abs_attos % attos_per_sec;
354
355        write!(f, "{}", whole_seconds)?;
356
357        if precision > 0 && fractional_attos > 0 {
358            let scale = 10u128.pow(18 - precision as u32);
359            let frac_value = fractional_attos / scale;
360
361            if frac_value > 0 {
362                f.write_str(".")?;
363
364                let mut digits = [0u8; 18];
365                let mut n = frac_value;
366
367                for i in (0..precision).rev() {
368                    digits[i] = (n % 10) as u8;
369                    n /= 10;
370                }
371
372                let last = digits[..precision]
373                    .iter()
374                    .rposition(|&d| d != 0)
375                    .unwrap_or(0);
376
377                for &d in &digits[..=last] {
378                    write!(f, "{}", d)?;
379                }
380            }
381        }
382
383        Ok(())
384    }
385}
386
387impl fmt::Debug for Dt {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        f.debug_struct("Dt")
390            .field("attos", &self.to_attos())
391            .field("scale", &self.scale)
392            .field("target", &self.target)
393            .finish()
394    }
395}
396
397#[cfg(feature = "wire")]
398impl Dt {
399    /// Current wire format version.
400    pub const WIRE_VERSION: u8 = 1;
401
402    /// Size of the canonical wire representation in bytes.
403    pub const WIRE_SIZE: usize = 19;
404
405    /// Serializes this `Dt` into a fixed 19-byte little-endian buffer using the
406    /// `attos: i128` + `scale: Scale` + `target: Scale` representation.
407    ///
408    /// ## Wire Format
409    ///
410    /// - Byte `0`: Version (`WIRE_VERSION`)
411    /// - Bytes `[1..17]`: total attoseconds as little-endian `i128`
412    /// - Byte `17`: scale as `u8` (enum discriminant)
413    /// - Byte `18`: target as `u8` (enum discriminant)
414    pub fn to_wire_bytes(&self) -> [u8; Self::WIRE_SIZE] {
415        let mut buf = [0u8; Self::WIRE_SIZE];
416        buf[0] = Self::WIRE_VERSION;
417        buf[1..17].copy_from_slice(&self.attos.to_le_bytes());
418        buf[17] = self.scale as u8;
419        buf[18] = self.target as u8;
420        buf
421    }
422
423    /// Deserializes a [`Dt`] from exactly 19 bytes of wire data.
424    ///
425    /// Returns `None` if the version byte is unknown, the length is wrong,
426    /// or the scale byte is not a valid `Scale` variant.
427    ///
428    /// ## Wire Format
429    ///
430    /// - Byte `0`: Version (`WIRE_VERSION`)
431    /// - Bytes `[1..17]`: total attoseconds as little-endian `i128`
432    /// - Byte `17`: scale as `u8` (enum discriminant)
433    /// - Byte `18`: target as `u8` (enum discriminant)
434    ///
435    /// ## Security
436    ///
437    /// Safe to call with completely untrusted input.
438    pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self> {
439        if bytes.len() != Self::WIRE_SIZE {
440            return None;
441        }
442
443        if bytes[0] != Self::WIRE_VERSION {
444            return None;
445        }
446
447        let attos = i128::from_le_bytes([
448            bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8],
449            bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15], bytes[16],
450        ]);
451
452        let scale = Scale::from_u8(bytes[17]);
453        let target = Scale::from_u8(bytes[18]);
454
455        Some(Dt::new(attos, scale, target))
456    }
457}