anytime 0.2.0

Ergonomic astronomical timescales in rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
use crate::anytime::AnyTime;
use crate::constants::{DAY_SECONDS, JD_TO_MJD, JD_TO_UNIX_SECONDS};
use crate::macros::impl_to_scale;
use crate::scales;
use chrono::{NaiveDate, NaiveDateTime, ParseError, TimeDelta, Timelike};
use std::cmp::Ordering;
use std::marker::PhantomData;
use std::ops::Sub;
use std::str::FromStr;

/// A time value associated with a specific time scale.
///
/// The scale is represented by the type parameter `S`, so conversions between
/// scales are checked by the compiler. The value has nanosecond precision and
/// can be represented as a Julian Date, Modified Julian Date, or Gregorian
/// date and time.
///
/// `Time<S>` implements [`FromStr`] for an ISO 8601 `T`-separated date and
/// time without an offset. The parsed date and time is interpreted in `S`.
///
/// # Examples
///
/// ```
/// use anytime::{Time, scales::UTC};
/// use chrono::NaiveDate;
///
/// let time = Time::<UTC>::from_gregorian(
///     NaiveDate::from_ymd_opt(2000, 1, 1)
///         .unwrap()
///         .and_hms_opt(12, 0, 0)
///         .unwrap(),
/// );
/// assert_eq!(time.jd(), 2_451_545.0);
/// ```
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Time<S> {
    /// Duration since Julian date epoch.
    pub(crate) value: TimeDelta,

    /// Marker for the time scale.
    _scale: PhantomData<S>,
}

impl<S> Clone for Time<S> {
    fn clone(&self) -> Self {
        Self {
            value: self.value,
            _scale: PhantomData,
        }
    }
}

/// Describes a time scale that can parameterize [`Time`].
///
/// The crate implements this trait for the marker types in [`crate::scales`].
/// It is public so generic code can refer to a time scale by its associated
/// name and properties.
pub trait Scale {
    /// The standard acronym for the scale.
    const NAME: &'static str;

    /// Whether the scale uses UTC's variable-length civil day.
    ///
    /// This is `true` only for [`crate::scales::UTC`]. Other supported scales
    /// use uniform 86,400-second days.
    const USES_UTC_DAY_SCALING: bool = false;
}

impl<S: Scale> Time<S> {
    pub(crate) fn new(value: TimeDelta) -> Self {
        Time {
            value,
            _scale: PhantomData,
        }
    }

    /// Returns the Julian Date representation of this time.
    ///
    /// The result is the sum of [`Self::split_jd`]'s two components. Use the
    /// split representation when preserving floating-point precision matters.
    ///
    /// # Examples
    ///
    /// ```
    /// use anytime::{Time, scales::TAI};
    ///
    /// let time = Time::<TAI>::from_jd(2_451_545.0);
    /// assert_eq!(time.jd(), 2_451_545.0);
    /// ```
    pub fn jd(&self) -> f64 {
        let seconds = self.value.num_seconds() as f64;
        let nanoseconds = self.value.subsec_nanos() as f64;
        (seconds + nanoseconds * 1e-9) / DAY_SECONDS
    }

    /// Returns the Julian Date as two components for improved precision.
    ///
    /// The returned pair `(jd1, jd2)` represents `jd1 + jd2`.
    pub fn split_jd(&self) -> (f64, f64) {
        let seconds = self.value.num_seconds();
        let nanoseconds = self.value.subsec_nanos();
        let jd1 = (seconds / 86400) as f64;
        let jd2 = ((seconds % 86400) as f64 + nanoseconds as f64 * 1e-9) / DAY_SECONDS;
        (jd1, jd2)
    }

    /// Returns the Modified Julian Date representation of this time.
    ///
    /// Modified Julian Date is Julian Date minus 2,400,000.5.
    pub fn mjd(&self) -> f64 {
        self.jd() - JD_TO_MJD
    }

    /// Creates a time from a Julian Date.
    ///
    /// The fractional part of the date is converted to nanoseconds and may
    /// therefore be rounded to the nearest nanosecond.
    pub fn from_jd(jd: f64) -> Self {
        let total_seconds = jd * DAY_SECONDS;
        let seconds = total_seconds.trunc() as i64;
        let nanoseconds = ((total_seconds.fract()) * 1e9) as u32;
        Time::new(TimeDelta::new(seconds, nanoseconds).unwrap())
    }

    /// Creates a time from a two-part Julian Date.
    ///
    /// Splitting a date into a large integral part and a small fractional part
    /// reduces loss of precision in calculations involving distant dates.
    ///
    /// # Examples
    ///
    /// ```
    /// use anytime::{Time, scales::UTC};
    ///
    /// let time = Time::<UTC>::from_split_jd(2_451_545.0, 0.0);
    /// assert_eq!(time.gregorian().to_string(), "2000-01-01 12:00:00");
    /// ```
    pub fn from_split_jd(jd1: f64, jd2: f64) -> Self {
        let jd1_seconds = (jd1 * DAY_SECONDS).round() as i64;
        let jd2_seconds = jd2 * DAY_SECONDS;
        let seconds = jd1_seconds + jd2_seconds.trunc() as i64;
        let nanoseconds = (jd2_seconds.fract() * 1e9).round() as i64;

        Time::new(TimeDelta::seconds(seconds) + TimeDelta::nanoseconds(nanoseconds))
    }

    /// Creates a time from a Modified Julian Date.
    pub fn from_mjd(mjd: f64) -> Self {
        Self::from_jd(mjd + JD_TO_MJD)
    }

    /// Returns this time as a proleptic Gregorian date and time in its scale.
    ///
    /// For UTC, a leap second is represented using Chrono's leap-second form,
    /// where the nanosecond component can reach one billion.
    ///
    /// # Examples
    ///
    /// ```
    /// use anytime::{Time, scales::UTC};
    ///
    /// let time = Time::<UTC>::from_jd(2_451_545.0);
    /// assert_eq!(time.gregorian().to_string(), "2000-01-01 12:00:00");
    /// ```
    pub fn gregorian(&self) -> NaiveDateTime {
        if !S::USES_UTC_DAY_SCALING {
            return uniform_gregorian(self.value);
        }

        let (jd1, jd2) = self.split_jd();
        let day = scales::common::utc_day(jd1, jd2);
        let midnight = Self::from_jd(day.midnight_jd).value;
        let nanoseconds = (day.scaled_fractional_day * DAY_SECONDS * 1e9).round() as i64;

        if nanoseconds < 86_400_000_000_000 {
            uniform_gregorian(midnight + TimeDelta::nanoseconds(nanoseconds))
        } else {
            let date = uniform_gregorian(midnight).date();
            date.and_hms_nano_opt(23, 59, 59, (nanoseconds - 86_399_000_000_000) as u32)
                .expect("valid Gregorian leap-second time")
        }
    }

    /// Creates a time from a proleptic Gregorian date and time in its scale.
    ///
    /// # Examples
    ///
    /// ```
    /// use anytime::{Time, scales::UTC};
    /// use chrono::NaiveDate;
    ///
    /// let date = NaiveDate::from_ymd_opt(2000, 1, 1)
    ///     .unwrap()
    ///     .and_hms_opt(12, 0, 0)
    ///     .unwrap();
    /// let time = Time::<UTC>::from_gregorian(date);
    /// assert_eq!(time.gregorian(), date);
    /// ```
    pub fn from_gregorian(gregorian: NaiveDateTime) -> Self {
        if !S::USES_UTC_DAY_SCALING {
            return Self::new(uniform_time(gregorian));
        }

        let midnight = gregorian
            .date()
            .and_hms_opt(0, 0, 0)
            .expect("valid Gregorian midnight");
        let midnight_value = uniform_time(midnight);
        let midnight_time = Self::new(midnight_value);
        let (jd1, jd2) = midnight_time.split_jd();
        let day = scales::common::utc_day(jd1, jd2);
        let nanoseconds = gregorian.time().num_seconds_from_midnight() as i64 * 1_000_000_000
            + gregorian.time().nanosecond() as i64;

        Self::new(
            midnight_value
                + TimeDelta::nanoseconds(
                    (nanoseconds as f64 / day.fractional_day_scale).round() as i64
                ),
        )
    }

    /// Creates a time from a proleptic Gregorian date and time in its scale.
    ///
    /// This is an alias for [`Self::from_gregorian`].
    pub fn from_datetime(datetime: NaiveDateTime) -> Self {
        Self::from_gregorian(datetime)
    }

    /// Parses an ISO 8601 `T`-separated date and time without an offset.
    ///
    /// The input must use the `YYYY-MM-DDTHH:MM:SS` form and may include a
    /// fractional-second component with up to nanosecond precision. The date
    /// and time is interpreted in this `Time` value's scale. Leap seconds use
    /// Chrono's `HH:MM:60` representation.
    pub fn from_isot_str(isot: &str) -> Result<Self, ParseError> {
        Self::from_str(isot, "%Y-%m-%dT%H:%M:%S%.f")
    }

    /// Parses an ISO space-separated date and time without an offset.
    ///
    /// The input must use the `YYYY-MM-DD HH:MM:SS` form and may include a
    /// fractional-second component with up to nanosecond precision. The date
    /// and time is interpreted in this `Time` value's scale.
    pub fn from_iso_str(iso: &str) -> Result<Self, ParseError> {
        Self::from_str(iso, "%Y-%m-%d %H:%M:%S%.f")
    }

    /// Parses a Chrono-formatted naive date and time in this scale.
    ///
    /// `format` accepts the full set of Chrono strftime specifiers.
    pub fn from_str(input: &str, format: &str) -> Result<Self, ParseError> {
        NaiveDateTime::parse_from_str(input, format).map(Self::from_datetime)
    }

    pub(crate) fn shift_scale_secs<T: Scale>(&self, seconds: f64) -> Time<T> {
        let nanoseconds = (seconds * 1e9).round() as i64;
        Time::<T>::new(self.value + TimeDelta::nanoseconds(nanoseconds))
    }
}

impl<S: Scale> FromStr for Time<S> {
    type Err = ParseError;

    /// Parses an offset-free ISO 8601 `T`-separated date and time in `S`.
    ///
    /// This is equivalent to [`Time::from_isot_str`].
    fn from_str(isot: &str) -> Result<Self, Self::Err> {
        Self::from_isot_str(isot)
    }
}

fn unix_epoch() -> NaiveDateTime {
    NaiveDate::from_ymd_opt(1970, 1, 1)
        .expect("valid Unix epoch date")
        .and_hms_opt(0, 0, 0)
        .expect("valid Unix epoch time")
}

fn uniform_gregorian(value: TimeDelta) -> NaiveDateTime {
    unix_epoch() + value - TimeDelta::seconds(JD_TO_UNIX_SECONDS)
}

fn uniform_time(gregorian: NaiveDateTime) -> TimeDelta {
    gregorian - unix_epoch() + TimeDelta::seconds(JD_TO_UNIX_SECONDS)
}

impl<S, T> Sub<Time<T>> for Time<S>
where
    Time<S>: Into<Time<scales::TAI>>,
    Time<T>: Into<Time<scales::TAI>>,
{
    type Output = TimeDelta;

    fn sub(self, other: Time<T>) -> TimeDelta {
        let lhs: Time<scales::TAI> = self.into();
        let rhs: Time<scales::TAI> = other.into();
        lhs.value - rhs.value
    }
}

impl<S, T> PartialEq<Time<T>> for Time<S>
where
    Time<T>: Into<Time<S>>,
{
    fn eq(&self, other: &Time<T>) -> bool {
        let other: Time<S> = (*other).clone().into();
        self.value == other.value
    }
}

impl<S> Eq for Time<S> {}

impl<S, T> PartialOrd<Time<T>> for Time<S>
where
    Time<T>: Into<Time<S>>,
{
    fn partial_cmp(&self, other: &Time<T>) -> Option<Ordering> {
        let other: Time<S> = (*other).clone().into();
        Some(self.value.cmp(&other.value))
    }
}

impl<S> Ord for Time<S> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.value.cmp(&other.value)
    }
}

impl_to_scale!(scales::BDT, bdt);
impl_to_scale!(scales::GLONASST, glonasst);
impl_to_scale!(scales::GPST, gpst);
impl_to_scale!(scales::GST, gst);
impl_to_scale!(scales::QZZST, qzzst);
impl_to_scale!(scales::TAI, tai);
impl_to_scale!(scales::TCB, tcb);
impl_to_scale!(scales::TCG, tcg);
impl_to_scale!(scales::TDB, tdb);
impl_to_scale!(scales::TT, tt);
impl_to_scale!(scales::UT1, ut1);
impl_to_scale!(scales::UTC, utc);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scales::{BDT, GLONASST, GPST, GST, QZZST, TAI, TCB, TCG, TDB, TT, UT1, UTC};

    macro_rules! assert_parses_datetime {
        ($scale:ty) => {{
            let datetime = NaiveDate::from_ymd_opt(2000, 1, 1)
                .unwrap()
                .and_hms_nano_opt(12, 0, 0, 123_456_789)
                .unwrap();
            let expected = Time::<$scale>::from_datetime(datetime);

            assert_eq!(expected, Time::<$scale>::from_gregorian(datetime));

            assert_eq!(
                Time::<$scale>::from_isot_str("2000-01-01T12:00:00.123456789").unwrap(),
                expected
            );
            assert_eq!(
                Time::<$scale>::from_iso_str("2000-01-01 12:00:00.123456789").unwrap(),
                expected
            );
            assert_eq!(
                Time::<$scale>::from_str("2000-01-01 12:00:00.123456789", "%Y-%m-%d %H:%M:%S%.f")
                    .unwrap(),
                expected
            );
            assert_eq!(
                "2000-01-01T12:00:00.123456789"
                    .parse::<Time<$scale>>()
                    .unwrap(),
                expected
            );
        }};
    }

    #[test]
    fn test_subtraction() {
        let tai1 = Time::<TAI>::new(TimeDelta::seconds(100));
        let tai2 = Time::<TAI>::new(TimeDelta::seconds(90));
        assert_eq!(tai1 - tai2, TimeDelta::seconds(10));

        let tai1 = Time::<TAI>::new(TimeDelta::seconds(90));
        let tai2 = Time::<TAI>::new(TimeDelta::seconds(100));
        assert_eq!(tai1 - tai2, TimeDelta::seconds(-10));

        let start = Time::<UTC>::from_gregorian(
            NaiveDate::from_ymd_opt(2016, 12, 31)
                .unwrap()
                .and_hms_opt(0, 0, 0)
                .unwrap(),
        );
        let end = Time::<UTC>::from_gregorian(
            NaiveDate::from_ymd_opt(2017, 1, 1)
                .unwrap()
                .and_hms_opt(0, 0, 0)
                .unwrap(),
        );
        assert_eq!(end - start, TimeDelta::seconds(86_401));
    }

    #[test]
    fn test_comparison() {
        let earlier = Time::<TAI>::new(TimeDelta::seconds(100));
        let same: Time<TT> = earlier.clone().into();
        let later = Time::<TAI>::new(TimeDelta::seconds(101));

        assert_eq!(earlier, same);
        assert_ne!(earlier, later);
        assert!(earlier < later);
        assert!(earlier <= same);
        assert!(later > same);
        assert!(later >= same);

        let later_tt: Time<TT> = later.clone().into();
        assert_eq!(same, earlier);
        assert_ne!(later_tt, earlier);
        assert!(same < later);
        assert!(same <= earlier);
        assert!(later_tt > earlier);
        assert!(later_tt >= earlier);
    }

    #[test]
    fn test_comparison_across_utc_leap_second() {
        let leap_second = Time::<UTC>::from_gregorian(
            NaiveDate::from_ymd_opt(2016, 12, 31)
                .unwrap()
                .and_hms_nano_opt(23, 59, 59, 1_000_000_000)
                .unwrap(),
        );
        let midnight = Time::<UTC>::from_gregorian(
            NaiveDate::from_ymd_opt(2017, 1, 1)
                .unwrap()
                .and_hms_opt(0, 0, 0)
                .unwrap(),
        );
        let midnight_tai: Time<TAI> = midnight.clone().into();

        assert!(leap_second < midnight_tai);
        assert!(midnight_tai > leap_second);
    }

    #[test]
    fn test_fractional_scale_shift() {
        let time = Time::<UTC>::new(TimeDelta::seconds(10));
        let shifted = time.shift_scale_secs::<UTC>(-1.422818);

        assert_eq!(shifted.value, TimeDelta::new(8, 577_182_000).unwrap());
    }

    #[test]
    fn test_jd() {
        assert_eq!(Time::<UTC>::from_jd(0.).jd(), 0.0);
    }

    #[test]
    fn test_split_jd() {
        assert_eq!(Time::<UTC>::from_jd(0.).split_jd(), (0.0, 0.0));
    }

    #[test]
    fn test_from_split_jd() {
        let time = Time::<UTC>::from_split_jd(2451545.0, 0.75);
        assert_eq!(time.value, TimeDelta::seconds(2451545 * 86400 + 64800));
    }

    #[test]
    fn test_mjd() {
        assert_eq!(Time::<UTC>::from_jd(0.).mjd(), -JD_TO_MJD);
    }

    #[test]
    fn test_gregorian() {
        let time = Time::<UTC>::from_split_jd(2_451_545.0, 0.0);
        let expected = NaiveDate::from_ymd_opt(2000, 1, 1)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();

        assert_eq!(time.gregorian(), expected);
    }

    #[test]
    fn test_from_gregorian() {
        let gregorian = NaiveDate::from_ymd_opt(2000, 1, 1)
            .unwrap()
            .and_hms_nano_opt(12, 0, 0, 123_456_789)
            .unwrap();
        let time = Time::<UTC>::from_gregorian(gregorian);

        assert_eq!(time.gregorian(), gregorian);
        assert_eq!(
            time.value,
            TimeDelta::seconds(2_451_545_i64 * 86_400) + TimeDelta::nanoseconds(123_456_789)
        );
    }

    #[test]
    fn test_typed_constructors_and_parsing() {
        assert_parses_datetime!(BDT);
        assert_parses_datetime!(GLONASST);
        assert_parses_datetime!(GPST);
        assert_parses_datetime!(GST);
        assert_parses_datetime!(QZZST);
        assert_parses_datetime!(TAI);
        assert_parses_datetime!(TCB);
        assert_parses_datetime!(TCG);
        assert_parses_datetime!(TDB);
        assert_parses_datetime!(TT);
        assert_parses_datetime!(UT1);
        assert_parses_datetime!(UTC);
        assert!(Time::<UTC>::from_isot_str("not a datetime").is_err());
        assert!(Time::<UTC>::from_isot_str("2000-01-01T12:00:00Z").is_err());
    }

    #[test]
    fn test_typed_parsers_support_optional_fractional_seconds_and_custom_formats() {
        let expected = Time::<TAI>::from_datetime(
            NaiveDate::from_ymd_opt(2000, 1, 1)
                .unwrap()
                .and_hms_opt(12, 0, 0)
                .unwrap(),
        );

        assert_eq!(
            Time::<TAI>::from_isot_str("2000-01-01T12:00:00").unwrap(),
            expected
        );
        assert_eq!(
            Time::<TAI>::from_iso_str("2000-01-01 12:00:00").unwrap(),
            expected
        );
        assert_eq!(
            Time::<TAI>::from_str("00/01/01 12:00", "%y/%m/%d %H:%M").unwrap(),
            expected
        );
    }

    #[test]
    fn test_typed_parsers_reject_invalid_inputs() {
        assert!(Time::<UTC>::from_iso_str("2000-01-01T12:00:00").is_err());
        assert!(Time::<UTC>::from_str("2000-01-01", "%Y-%m-%dT%H:%M:%S").is_err());
        assert!("2000-01-01T12:00:00Z".parse::<Time<UTC>>().is_err());
        assert!(Time::<UTC>::from_isot_str("2016-12-31T23:59:61").is_err());
    }

    #[test]
    fn test_utc_gregorian_leap_second() {
        let gregorian = NaiveDate::from_ymd_opt(2016, 12, 31)
            .unwrap()
            .and_hms_nano_opt(23, 59, 59, 1_000_000_000)
            .unwrap();
        let time = Time::<UTC>::from_gregorian(gregorian);

        assert_eq!(time.gregorian(), gregorian);
        assert_eq!(
            Time::<UTC>::from_isot_str("2016-12-31T23:59:60").unwrap(),
            time
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_round_trip() {
        let time = Time::<UTC>::from_split_jd(2_451_545.0, 0.123_456_789);
        let json = serde_json::to_string(&time).unwrap();

        assert_eq!(serde_json::from_str::<Time<UTC>>(&json).unwrap(), time);
    }
}