deep_time/dt/mod.rs
1mod arithmetic;
2mod arithmetic_calendar;
3mod constructors;
4mod conveniences;
5mod conversions;
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::to`](../struct.Dt.html#method.to)
101/// - [`Dt::convert`](../struct.Dt.html#method.convert)
102/// - [`Dt::to_tai`](../struct.Dt.html#method.to_tai)
103/// - [`Dt::from_sec`](../struct.Dt.html#method.from_sec)
104/// - [`Dt::to_sec64`](../struct.Dt.html#method.to_sec64)
105/// - [`Dt::from_attos`](../struct.Dt.html#method.from_attos)
106/// - [`Dt::convert_internal`](../struct.Dt.html#method.convert_internal)
107/// - [`Dt::to_unix`](../struct.Dt.html#method.to_unix)
108/// - [`Dt::to_ntp`](../struct.Dt.html#method.to_ntp)
109/// - [`Dt::to_gps_wk_and_tow`](../struct.Dt.html#method.to_gps_wk_and_tow)
110///
111/// ### Conversions from and to types from other libraries
112///
113/// - [`Dt::to_hifitime_epoch`](../struct.Dt.html#method.to_hifitime_epoch)
114/// - [`Dt::to_jiff_timestamp`](../struct.Dt.html#method.to_jiff_timestamp)
115/// - [`Dt::to_chrono_datetime_utc`](../struct.Dt.html#method.to_chrono_datetime_utc)
116/// - [`Dt::from_hifitime_epoch`](../struct.Dt.html#method.from_hifitime_epoch)
117/// - [`Dt::from_jiff_timestamp`](../struct.Dt.html#method.from_jiff_timestamp)
118/// - [`Dt::from_chrono_datetime_utc`](../struct.Dt.html#method.from_chrono_datetime_utc)
119///
120/// ## Examples
121///
122/// ### Parsing a date
123///
124/// ```rust
125/// use deep_time::{Dt, Scale};
126///
127/// // uses impl FromStr but Dt::parse provides the same functionality
128/// let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
129///
130/// let ymd = x.to_ymd();
131/// assert_eq!(ymd.yr(), 2000);
132/// assert_eq!(ymd.mo(), 1);
133/// assert_eq!(ymd.day(), 1);
134/// assert_eq!(ymd.hr(), 12);
135/// assert_eq!(ymd.min(), 0);
136/// assert_eq!(ymd.sec(), 0);
137/// assert_eq!(ymd.attos(), 0);
138/// ```
139///
140/// ### Outputting a date to string / bytes
141///
142/// ```rust
143/// # #[cfg(all(feature = "jiff-tz", feature = "parse"))]
144/// # {
145/// use deep_time::{Dt, Lang, Scale};
146///
147/// let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
148///
149/// let s = x
150/// .to_str_in_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York", Lang::En)
151/// .unwrap();
152/// let b = x
153/// .to_str_lite_in_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York", Lang::En)
154/// .unwrap();
155///
156/// assert_eq!(s, "Saturday, January 01, 2000 07:00:00 America/New_York");
157/// assert_eq!(b.as_str(), "Saturday, January 01, 2000 07:00:00 America/New_York");
158/// # }
159/// ```
160///
161/// ### Creating a unix timestamp in milliseconds
162///
163/// ```rust
164/// use deep_time::{Dt, Scale};
165///
166/// // this fn converts from UTC and creates a TAI Dt
167/// let dt = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::UTC);
168///
169/// // dt is internally TAI but has a UTC tag
170/// let unix_ms = dt.to_unix().to_ms();
171///
172/// // unix timestamp in ms for 2000-01-01 noon UTC
173/// assert_eq!(unix_ms, 946728000000);
174/// ```
175///
176/// ### Converting time scales
177///
178/// Many functions such as
179/// [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd) will convert to
180/// `TAI` from the [`Dt`]s current `scale` then to the [`Dt`]s `target`
181/// [`Scale`] prior to producing an output.
182///
183/// So you don't necessarily have to convert time scales prior to using
184/// many of the output functions. You just have to change the `target`
185/// time scale.
186///
187/// #### Using the target field
188///
189/// ```rust
190/// use deep_time::{Dt, Lang, Scale};
191///
192/// // Leap seconds were added to the secounds count
193/// // This Dt has attos that are now on the TAI timescale
194/// let dt = Dt::from_ymd(2025, 1, 1, 0, 0, 0, 0, Scale::UTC);
195///
196/// // The internal target is currently UTC so we don't need to do
197/// // anything to output back to UTC and round trip
198/// let bytes = dt.to_str_lite("%d %m %Y %H:%M:%S", Lang::En).unwrap();
199///
200/// assert_eq!(bytes.as_str(), "01 01 2025 00:00:00");
201///
202/// // Perhaps we want to make a GPS timestamp out of our Dt
203/// // If we want it to be on the GPS time scale we have to set the
204/// // target prior to calling to_gps()
205/// let gps = dt.target(Scale::GPS).to_gps().to_sec_f();
206/// ```
207///
208/// #### Converting the internal attos to a new time scale
209///
210/// ```rust
211/// use deep_time::{Dt, Scale};
212///
213/// // this fn converts from UTC and creates a TAI Dt
214/// let dt = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::UTC);
215///
216/// // to tdb
217/// let tdb = dt.to(Scale::TDB);
218///
219/// // then to tt, the current scale is TDB
220/// let tt = tdb.to(Scale::TT);
221///
222/// // then back to TAI
223/// let tai = tt.to(Scale::TAI);
224///
225/// // round trip equality
226/// assert_eq!(dt, tai);
227/// ```
228///
229/// ### Performing some basic calendar aware math
230///
231/// ```rust
232/// use deep_time::{Dt, Scale};
233///
234/// let x = Dt::from_ymd(2000, 2, 29, 0, 0, 0, 0, Scale::UTC).to_ymd();
235/// let x = x.add_yr(1);
236///
237/// assert_eq!(x.day(), 28);
238/// ```
239///
240/// ### Changing a dates format
241///
242/// ```rust
243/// use deep_time::{Dt, Lang, StrPTimeFmt};
244///
245/// let fmt = Dt::parse_fmt("%Y-%m-%dT%H:%M:%S").unwrap();
246///
247/// # #[cfg(feature = "alloc")]
248/// let s = fmt.to_str("2000-01-01T12:00:00", "%d %m %Y %H:%M:%S", false, false, false, Lang::En).unwrap();
249///
250/// # #[cfg(feature = "alloc")]
251/// assert_eq!(s, "01 01 2000 12:00:00", "expected: {}, got: {}", "01 01 2000 12:00:00", s);
252/// ```
253#[derive(Clone, Copy)]
254#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
255#[cfg_attr(feature = "js", derive(tsify::Tsify))]
256pub struct Dt {
257 pub attos: i128,
258 pub scale: Scale,
259 pub target: Scale,
260}
261
262impl Dt {
263 /// Returns a new [`Dt`] with the `target` field set to the given
264 /// `t` arg.
265 #[inline(always)]
266 pub const fn target(&self, t: Scale) -> Dt {
267 Dt::new(self.attos, self.scale, t)
268 }
269
270 #[inline(always)]
271 pub(crate) const fn with(&self, s: Scale) -> Dt {
272 Dt::new(self.attos, s, self.target)
273 }
274}
275
276impl Default for Dt {
277 fn default() -> Dt {
278 Self::ZERO
279 }
280}
281
282impl fmt::Display for Dt {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 let total = self.to_attos();
285 let precision = f.precision().unwrap_or(9).min(18);
286
287 let is_negative = total < 0;
288 let abs_attos = if is_negative {
289 total.wrapping_neg() as u128
290 } else {
291 total as u128
292 };
293
294 if is_negative {
295 f.write_str("-")?;
296 } else if f.sign_plus() {
297 f.write_str("+")?;
298 }
299
300 let attos_per_sec = ATTOS_PER_SEC as u128;
301 let whole_seconds = abs_attos / attos_per_sec;
302 let fractional_attos = abs_attos % attos_per_sec;
303
304 // Integer seconds
305 write!(f, "{}", whole_seconds)?;
306
307 // Fractional part (only when requested *and* non-zero after truncation)
308 if precision > 0 && fractional_attos > 0 {
309 let scale = 10u128.pow(18 - precision as u32);
310 let frac_value = fractional_attos / scale;
311
312 if frac_value > 0 {
313 write!(f, ".{:0>width$}", frac_value, width = precision)?;
314 }
315 }
316
317 Ok(())
318 }
319}
320
321impl fmt::Debug for Dt {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 f.debug_struct("Dt")
324 .field("attos", &self.to_attos())
325 .field("scale", &self.scale)
326 .field("target", &self.target)
327 .finish()
328 }
329}