Skip to main content

deep_time/ymdhms/
mod.rs

1use crate::{ATTOS_PER_SEC_I128, Dt, Scale, Weekday};
2
3mod to_str;
4
5/// Combined Gregorian date + wall time with subsecond precision.
6///
7/// Has some basic calendar aware math, but not time zone aware.
8///
9/// ## Examples
10///
11/// **Creating a** [`YmdHms`].
12///
13/// ```rust
14/// use deep_time::{Dt, Scale};
15///
16/// // clamped to 29
17/// let x = Dt::from_ymd(2000, 2, 30, 0, 0, 0, 0, Scale::UTC).to_ymd();
18///
19/// assert_eq!(x.day(), 29);
20/// ```
21///
22/// **Adding a year.** 2000 is a leap year and Feb. 29th is possible, but
23/// 2001 isn't a leap year so the day is clamped to the 28th.
24///
25/// ```rust
26/// use deep_time::{Dt, Scale};
27///
28/// let x = Dt::from_ymd(2000, 2, 29, 0, 0, 0, 0, Scale::UTC).to_ymd();
29/// let x = x.add_yr(1);
30///
31/// assert_eq!(x.day(), 28);
32/// ```
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34#[cfg_attr(feature = "js", derive(tsify::Tsify))]
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
36pub struct YmdHms {
37    pub(crate) yr: i64,
38    pub(crate) mo: u8,
39    pub(crate) day: u8,
40    pub(crate) hr: u8,
41    pub(crate) min: u8,
42    pub(crate) sec: u8,    // 0–60 (60 only during leap seconds)
43    pub(crate) attos: u64, // attoseconds (0 ≤ subsec < 10¹⁸)
44    pub(crate) unix_attosec: i128,
45    pub(crate) scale: Scale,
46}
47
48impl YmdHms {
49    /// Reconstructs a [`Dt`].
50    #[inline]
51    pub fn to_dt(&self) -> Dt {
52        Dt::from_ymd(
53            self.yr, self.mo, self.day, self.hr, self.min, self.sec, self.attos, self.scale,
54        )
55    }
56
57    #[inline(always)]
58    fn reconstruct(
59        yr: i64,
60        mo: u8,
61        day: u8,
62        hr: u8,
63        min: u8,
64        sec: u8,
65        attos: u64,
66        scale: Scale,
67    ) -> Self {
68        Dt::from_ymd(yr, mo, day, hr, min, sec, attos, scale).to_ymd()
69    }
70
71    /// Adds (or subtracts) whole years, preserving month and day-of-month.
72    /// Negative values subtract years. Uses standard last-day-of-month clamping.
73    pub fn add_yr(&self, years: i64) -> Self {
74        if years == 0 {
75            return *self;
76        }
77        let new_yr = self.yr.saturating_add(years);
78        let max_day = Dt::days_in_month(new_yr, self.mo);
79        let new_day = Dt::clamp_u8(self.day, 1, max_day);
80        Self::reconstruct(
81            new_yr, self.mo, new_day, self.hr, self.min, self.sec, self.attos, self.scale,
82        )
83    }
84
85    /// Adds (or subtracts) whole months. Negative values subtract months.
86    /// Uses `i128` total-month arithmetic to avoid overflow at extreme years.
87    pub fn add_mo(&self, months: i64) -> Self {
88        if months == 0 {
89            return *self;
90        }
91        let yr = self.yr as i128;
92        let mo = self.mo as i128;
93        let delta = months as i128;
94
95        let total_months = yr * 12 + (mo - 1) + delta;
96
97        let new_yr = Dt::i128_to_i64(total_months.div_euclid(12));
98        let new_mo = Dt::clamp_u8((total_months.rem_euclid(12) + 1) as u8, 1, 12);
99
100        let max_day = Dt::days_in_month(new_yr, new_mo);
101        let new_day = Dt::clamp_u8(self.day, 1, max_day);
102
103        Self::reconstruct(
104            new_yr, new_mo, new_day, self.hr, self.min, self.sec, self.attos, self.scale,
105        )
106    }
107
108    /// Adds (or subtracts) calendar days using Julian Day arithmetic.
109    /// Negative values subtract days.
110    pub fn add_days(&self, days: i64) -> Self {
111        if days == 0 {
112            return *self;
113        }
114        let jd = Dt::ymd_to_jd(self.yr, self.mo, self.day);
115        let new_jd = jd.saturating_add(days);
116        let (new_yr, new_mo, new_day) = Dt::jd_to_ymd(new_jd);
117        Self::reconstruct(
118            new_yr, new_mo, new_day, self.hr, self.min, self.sec, self.attos, self.scale,
119        )
120    }
121
122    #[inline]
123    pub fn add_wk(&self, weeks: i64) -> Self {
124        self.add_days(weeks.saturating_mul(7))
125    }
126
127    #[inline(never)]
128    fn _add_attos(&self, attos_delta: i128) -> Self {
129        let tai = Dt::from_ymd(
130            self.yr, self.mo, self.day, self.hr, self.min, self.sec, self.attos, self.scale,
131        );
132        let new_tai = tai.add(Dt::span(attos_delta));
133        new_tai.to_ymd()
134    }
135
136    #[inline]
137    pub fn add_attos(&self, attos: i128) -> Self {
138        self._add_attos(attos)
139    }
140
141    #[inline]
142    pub fn add_sec(&self, sec: i64) -> Self {
143        self._add_attos(sec as i128 * ATTOS_PER_SEC_I128)
144    }
145
146    #[inline]
147    pub fn add_min(&self, min: i64) -> Self {
148        self._add_attos(min as i128 * 60 * ATTOS_PER_SEC_I128)
149    }
150
151    #[inline]
152    pub fn add_hr(&self, hr: i64) -> Self {
153        self._add_attos(hr as i128 * 3600 * ATTOS_PER_SEC_I128)
154    }
155
156    #[inline]
157    pub fn yr(&self) -> i64 {
158        self.yr
159    }
160
161    #[inline]
162    pub fn mo(&self) -> u8 {
163        self.mo
164    }
165
166    #[inline]
167    pub fn day(&self) -> u8 {
168        self.day
169    }
170
171    #[inline]
172    pub fn hr(&self) -> u8 {
173        self.hr
174    }
175
176    #[inline]
177    pub fn min(&self) -> u8 {
178        self.min
179    }
180
181    #[inline]
182    pub fn sec(&self) -> u8 {
183        self.sec
184    }
185
186    #[inline]
187    pub fn attos(&self) -> u64 {
188        self.attos
189    }
190
191    /// Attoseconds since 1970-01-01 midnight, on whatever time scale
192    /// the object was created on.
193    #[inline]
194    pub fn unix_attosec(&self) -> i128 {
195        self.unix_attosec
196    }
197
198    /// The time scale that the object was created on.
199    #[inline]
200    pub fn scale(&self) -> Scale {
201        self.scale
202    }
203
204    #[inline]
205    pub fn iso_yr(&self) -> i64 {
206        let (iso_yr, _, _) = Dt::_to_iso_wk_date(self.yr, self.mo, self.day);
207        iso_yr
208    }
209
210    #[inline]
211    pub fn iso_wk(&self) -> u8 {
212        let (_, iso_wk, _) = Dt::_to_iso_wk_date(self.yr, self.mo, self.day);
213        iso_wk
214    }
215
216    #[inline]
217    pub fn day_of_yr(&self) -> u16 {
218        Dt::_day_of_yr(self.yr, self.mo, self.day)
219    }
220
221    #[inline]
222    pub fn wkday(&self) -> Weekday {
223        let jd = Dt::ymd_to_jd(self.yr, self.mo, self.day);
224        Weekday::from_sunday_0_based(Dt::jd_to_wkday(jd)).unwrap_or_default()
225    }
226
227    #[inline]
228    pub fn wk_of_yr_sun(&self) -> u8 {
229        Dt::_wk_sun(self.yr, self.day_of_yr())
230    }
231
232    #[inline]
233    pub fn wk_of_yr_mon(&self) -> u8 {
234        Dt::_wk_mon(self.yr, self.day_of_yr())
235    }
236
237    /// Returns the Unix timestamp since 1970-01-01 00:00:00 as a tuple of
238    /// `(whole_seconds, attoseconds)`.
239    ///
240    /// - The timestamp will be on whatever [`Scale`] the [`DateTime`] was created on.
241    /// - `whole_seconds` can be negative (for dates before 1970).
242    /// - The fractional part (`attoseconds`) is always in the range `0..=999_999_999_999_999_999`.
243    pub const fn unix_timestamp(&self) -> (i64, u64) {
244        const ATTOS_PER_SEC_I128: i128 = 1_000_000_000_000_000_000;
245        let total = self.unix_attosec;
246        let secs = (total / ATTOS_PER_SEC_I128) as i64;
247        let frac = (total % ATTOS_PER_SEC_I128).unsigned_abs() as u64;
248        (secs, frac)
249    }
250}