Skip to main content

deep_time/dt/
mod.rs

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