Skip to main content

deep_time/dt/
mod.rs

1mod arithmetic;
2mod constructors;
3mod conveniences;
4mod conversions;
5mod decimal_year;
6mod from_ccsds;
7mod from_str;
8mod gregorian;
9mod julian_date;
10mod ops;
11mod tdb;
12mod to_bin_ccsds;
13mod to_str;
14
15pub mod lunar;
16pub mod numbers_traits;
17pub mod trajectory;
18
19#[cfg(feature = "alloc")]
20mod to_str_ccsds;
21
22#[cfg(feature = "mars")]
23pub mod mars;
24
25#[cfg(feature = "hifitime")]
26mod hifitime;
27
28#[cfg(feature = "chrono")]
29mod chrono;
30
31#[cfg(feature = "jiff")]
32mod jiff;
33
34use crate::{ATTOS_PER_SEC, Scale};
35use core::fmt;
36
37/// **The library's central time type.** A high-precision instant/duration with attosecond
38/// resolution.
39///
40/// **Fields:**
41///
42/// - pub attos: [`i128`] - total time in attoseconds since the reference epoch
43///   (2000-01-01 noon), as a signed integer. Negative values represent times
44///   before the epoch.
45/// - pub scale: [`Scale`] - the current time scale of the object.
46/// - pub target: [`Scale`] - a target time scale used by many output functions such as
47///   [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd) and
48///   [`Dt::to_unix`](../struct.Dt.html#method.to_unix).
49///
50/// **Notes:**
51///
52/// - In theory it supports a range of roughly ±5.39 trillion years but many of the to and
53///   from functions cap at i64 seconds, which can mean a range of ±292 billion years in practice.
54/// - Implements `Copy` and `Clone`. Optional derives for `serde` and `tsify` are available
55///   behind the corresponding features.
56/// - A wide range of math is available for this type, but it's not calendar aware, for basic
57///   calendar aware math use the [`YmdHms`] type.
58///
59/// ## Reference epoch and scales
60///
61/// - The librarys epoch for nearly all functionality such as the conversion functions is
62///   **2000-01-01 noon**. See also: [`Scale`](../enum.Scale.html).
63/// - Leap-second handling follows the chosen `Scale` (UTC, UtcSpice, UtcHist).
64///
65/// ## See also (non-exhaustive list)
66///
67/// ### From and to calendar dates
68///
69/// - [`Dt::from_ymd`](../struct.Dt.html#method.from_ymd)
70/// - [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd)
71///
72/// ### From and to str and bytes
73///
74/// Some of these require the alloc feature, they're marked with *
75///
76/// - [`Dt::from_str_parse`](../struct.Dt.html#method.from_str_parse)*
77/// - [`Dt::from_str_ccsds`](../struct.Dt.html#method.from_str_ccsds)
78/// - [`Dt::parse`](../struct.Dt.html#method.parse)
79/// - [`Dt::from_str`](../struct.Dt.html#method.from_str)
80/// - [`Dt::to_str`](../struct.Dt.html#method.to_str)*
81/// - [`Dt::to_str_in_offset`](../struct.Dt.html#method.to_str_in_offset)*
82/// - [`Dt::to_str_in_tz`](../struct.Dt.html#method.to_str_in_tz)*
83/// - [`Dt::to_str_iso8601`](../struct.Dt.html#method.to_str_iso8601)*
84/// - [`Dt::to_str_lite`](../struct.Dt.html#method.to_str_lite)
85/// - [`Dt::to_str_lite_in_offset`](../struct.Dt.html#method.to_str_lite_in_offset)
86/// - [`Dt::to_str_lite_in_tz`](../struct.Dt.html#method.to_str_lite_in_tz)
87///
88/// ### From and to julian dates
89///
90/// - [`Dt::from_jd_f`](../struct.Dt.html#method.from_jd_f)
91/// - [`Dt::from_mjd_f`](../struct.Dt.html#method.from_mjd_f)
92/// - [`Dt::to_jd_f`](../struct.Dt.html#method.to_jd_f)
93/// - [`Dt::to_mjd_f`](../struct.Dt.html#method.to_mjd_f)
94/// - [`Dt::ymd_to_jd`](../struct.Dt.html#method.ymd_to_jd)
95/// - [`Dt::jd_to_ymd`](../struct.Dt.html#method.jd_to_ymd)
96///
97/// ### Conversions, time scales etc.
98///
99/// - [`Dt::target`](../struct.Dt.html#method.target)
100/// - [`Dt::from_sec`](../struct.Dt.html#method.from_sec)
101/// - [`Dt::to_sec64`](../struct.Dt.html#method.to_sec64)
102/// - [`Dt::from_attos`](../struct.Dt.html#method.from_attos)
103/// - [`Dt::convert_internal`](../struct.Dt.html#method.convert_internal)
104/// - [`Dt::to_unix`](../struct.Dt.html#method.to_unix)
105/// - [`Dt::to_ntp`](../struct.Dt.html#method.to_ntp)
106/// - [`Dt::to_gps_wk_and_tow`](../struct.Dt.html#method.to_gps_wk_and_tow)
107///
108/// ### Conversions from and to types from other libraries
109///
110/// - [`Dt::to_hifitime_epoch`](../struct.Dt.html#method.to_hifitime_epoch)
111/// - [`Dt::to_jiff_timestamp`](../struct.Dt.html#method.to_jiff_timestamp)
112/// - [`Dt::to_chrono_datetime_utc`](../struct.Dt.html#method.to_chrono_datetime_utc)
113/// - [`Dt::from_hifitime_epoch`](../struct.Dt.html#method.from_hifitime_epoch)
114/// - [`Dt::from_jiff_timestamp`](../struct.Dt.html#method.from_jiff_timestamp)
115/// - [`Dt::from_chrono_datetime_utc`](../struct.Dt.html#method.from_chrono_datetime_utc)
116///
117/// ## Examples
118///
119/// ### Parsing a date
120///
121/// ```rust
122/// use deep_time::{Dt, Scale};
123///
124/// // uses impl FromStr but Dt::parse provides the same functionality
125/// let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
126///
127/// let ymd = x.to_ymd();
128/// assert_eq!(ymd.yr(), 2000);
129/// assert_eq!(ymd.mo(), 1);
130/// assert_eq!(ymd.day(), 1);
131/// assert_eq!(ymd.hr(), 12);
132/// assert_eq!(ymd.min(), 0);
133/// assert_eq!(ymd.sec(), 0);
134/// assert_eq!(ymd.attos(), 0);
135/// ```
136///
137/// ### Outputting a date to string / bytes
138///
139/// ```rust
140/// # #[cfg(all(feature = "tz", feature = "parse"))]
141/// # {
142/// use deep_time::{Dt, Lang, Scale};
143///
144/// let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
145///
146/// let s = x
147///  .to_str_in_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York", Lang::En)
148///  .unwrap();
149/// let b = x
150///  .to_str_lite_in_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York", Lang::En)
151///  .unwrap();
152///
153/// assert_eq!(s, "Saturday, January 01, 2000 07:00:00 America/New_York");
154/// assert_eq!(b.as_str().unwrap(), "Saturday, January 01, 2000 07:00:00 America/New_York");
155/// # }
156/// ```
157///
158/// ### Creating a unix timestamp in milliseconds
159///
160/// ```rust
161/// use deep_time::{Dt, Scale};
162///
163/// // this fn converts from UTC and creates a TAI Dt
164/// let dt = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::UTC);
165///
166/// // dt is internally TAI but has a UTC tag
167/// let unix_ms = dt.to_unix().to_ms();
168///
169/// // unix timestamp in ms for 2000-01-01 noon UTC
170/// assert_eq!(unix_ms, 946728000000);
171/// ```
172///
173/// ### Converting time scales
174///
175/// Many functions such as
176/// [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd) will convert to
177/// `TAI` from the [`Dt`]s current `scale` then to the [`Dt`]s `target`
178/// [`Scale`] prior to producing an output.
179///
180/// So you don't necessarily have to convert time scales prior to using
181/// many of the output functions. You just have to change the `target`
182/// time scale.
183///
184/// #### Using the target field
185///
186/// ```rust
187/// use deep_time::{Dt, Lang, Scale};
188///
189/// // Leap seconds were added to the secounds count
190/// // This Dt has attos that are now on the TAI timescale
191/// let dt = Dt::from_ymd(2025, 1, 1, 0, 0, 0, 0, Scale::UTC);
192///
193/// // The internal target is currently UTC so we don't need to do
194/// // anything to output back to UTC and round trip
195/// let bytes = dt.to_str_lite("%d %m %Y %H:%M:%S", Lang::En).unwrap();
196///
197/// assert_eq!(bytes.as_str().unwrap(), "01 01 2025 00:00:00");
198///
199/// // Perhaps we want to make a GPS timestamp out of our Dt
200/// // If we want it to be on the GPS time scale we have to set the
201/// // target prior to calling to_gps()
202/// let gps = dt.target(Scale::GPS).to_gps().to_sec_f();
203/// ```
204///
205/// #### Converting the internal attos to a new time scale
206///
207/// ```rust
208/// use deep_time::{Dt, Scale};
209///
210/// // this fn converts from UTC and creates a TAI Dt
211/// let dt = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::UTC);
212///
213/// // to tdb
214/// let tdb = dt.to(Scale::TDB);
215///
216/// // then to tt, the current scale is TDB
217/// let tt = tdb.to(Scale::TT);
218///
219/// // then back to TAI
220/// let tai = tt.to(Scale::TAI);
221///
222/// // round trip equality
223/// assert_eq!(dt, tai);
224/// ```
225///
226/// ### Performing some basic calendar aware math
227///
228/// ```rust
229/// use deep_time::{Dt, Scale};
230///
231/// let x = Dt::from_ymd(2000, 2, 29, 0, 0, 0, 0, Scale::UTC).to_ymd();
232/// let x = x.add_yr(1);
233///
234/// assert_eq!(x.day(), 28);
235/// ```
236///
237/// ### Changing a dates format
238///
239/// ```rust
240/// use deep_time::{Dt, Lang, StrPTimeFmt};
241///
242/// let fmt = Dt::parse_fmt("%Y-%m-%dT%H:%M:%S").unwrap();
243///
244/// # #[cfg(feature = "alloc")]
245/// let s = fmt.to_str("2000-01-01T12:00:00", "%d %m %Y %H:%M:%S", false, false, false, Lang::En).unwrap();
246///
247/// # #[cfg(feature = "alloc")]
248/// assert_eq!(s, "01 01 2000 12:00:00", "expected: {}, got: {}", "01 01 2000 12:00:00", s);
249/// ```
250#[derive(Clone, Copy)]
251#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
252#[cfg_attr(feature = "js", derive(tsify::Tsify))]
253pub struct Dt {
254    pub attos: i128,
255    pub scale: Scale,
256    pub target: Scale,
257}
258
259impl Dt {
260    /// Returns a new [`Dt`] with the `target` field set to the given
261    /// `t` arg.
262    #[inline(always)]
263    pub const fn target(&self, t: Scale) -> Dt {
264        Dt::new(self.attos, self.scale, t)
265    }
266
267    #[inline(always)]
268    pub(crate) const fn with(&self, s: Scale) -> Dt {
269        Dt::new(self.attos, s, self.target)
270    }
271}
272
273impl Default for Dt {
274    fn default() -> Dt {
275        Self::ZERO
276    }
277}
278
279impl fmt::Display for Dt {
280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281        let total = self.to_attos();
282        let precision = f.precision().unwrap_or(9).min(18);
283
284        let is_negative = total < 0;
285        let abs_attos = if is_negative {
286            total.wrapping_neg() as u128
287        } else {
288            total as u128
289        };
290
291        if is_negative {
292            f.write_str("-")?;
293        } else if f.sign_plus() {
294            f.write_str("+")?;
295        }
296
297        let attos_per_sec = ATTOS_PER_SEC as u128;
298        let whole_seconds = abs_attos / attos_per_sec;
299        let fractional_attos = abs_attos % attos_per_sec;
300
301        // Integer seconds
302        write!(f, "{}", whole_seconds)?;
303
304        // Fractional part (only when requested *and* non-zero after truncation)
305        if precision > 0 && fractional_attos > 0 {
306            let scale = 10u128.pow(18 - precision as u32);
307            let frac_value = fractional_attos / scale;
308
309            if frac_value > 0 {
310                write!(f, ".{:0>width$}", frac_value, width = precision)?;
311            }
312        }
313
314        Ok(())
315    }
316}
317
318impl fmt::Debug for Dt {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        f.debug_struct("Dt")
321            .field("attos", &self.to_attos())
322            .field("scale", &self.scale)
323            .field("target", &self.target)
324            .finish()
325    }
326}