ako 0.0.3

Ako is a Rust crate that offers a practical and human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps.
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
576
use core::fmt::{self, Debug, Display, Formatter};
use core::ops::{Add, Sub};
use core::str::FromStr;
use core::time::Duration;

use crate::calendar::Iso;
use crate::{AsMoment, AsTime, Calendar, Date, DateTime, PlainTime, TimeInterval, TimeZone};

const SECONDS_IN_DAY: i64 = 86_400;

/// A precise **moment** in time.
///
/// A [`Moment`] has no concept of a particular time zone or calendar. It represents a single
/// point in time that can be globally agreed upon.
///
/// Internally, moments are represented in the [Coordinated Universal Time] (UTC) time scale
/// as the signed number of seconds and sub-second nanoseconds since the [Unix epoch] at January 1, 1970.
/// A positive number of seconds indicates a moment after the Unix epoch where a negative number of
/// seconds indicates a moment before the Unix epoch.
///
/// A [`Moment`] can be created from and displayed as a [RFC 3339] string like `2018-02-15T03:41:23Z` with
/// the [`FromStr`][core::str::FromStr] and [`Display`][core::fmt::Display] traits.
///
/// [Unix epoch]: https://en.wikipedia.org/wiki/Unix_time
/// [Unix time]: https://en.wikipedia.org/wiki/Unix_time
/// [Julian Day]: https://en.wikipedia.org/wiki/Julian_day
/// [Coordinated Universal Time]: https://en.wikipedia.org/wiki/Coordinated_Universal_Time
/// [RFC 3339]: https://datatracker.ietf.org/doc/html/rfc3339
///
/// # Interoperability
///
/// The [`Moment`] type can be created from and converted to many representations of exact time
/// and other time scales, such as [Unix time], a [Julian day], or [RFC 3339].<sup>†</sup>
///
/// <sup>†</sup><sub>Please feel free to [open an issue](https://github.com/transact-rs/ako/issues/new) requesting additional
/// representations for conversion to and from.</sub>
///
/// ## [Unix Time]
///
/// [Unix time] is widely used as a storage and transmission format for date and time. It
/// is the count of non-leap seconds from January 1, 1970, at 00:00:00 UTC.
///
/// #### Create a [`Moment`] from a Unix time, in milliseconds
///
/// ```rust
/// use ako::Moment;
///
/// let moment = Moment::from_unix_milliseconds(1727597174768);
///
/// assert_eq!(moment.to_string(), "2024-09-29T08:06:14.768000000Z");
/// ```
///
/// #### Get the current time as a Unix timestamp
///
/// ```rust
/// use ako::Moment;
///
/// // secs is the number of seconds since the Unix epoch
/// // nsec is the sub-second nanoseconds
/// let (secs, nsec) = Moment::now().to_unix();
/// ```
///
/// ## [`SystemTime`][std::time::SystemTime] ([`std`])
///
/// [`Moment`] and [`std::time::SystemTime`][std::time::SystemTime] can be freely converted between each other.
///
/// #### Get a value of [`SystemTime`][std::time::SystemTime] from RFC 3339
///
/// ```rust
/// use std::time::SystemTime;
/// use ako::Moment;
///
/// # fn main() -> ako::Result<()> {
/// let moment: Moment = "2018-02-15T03:41:23Z".parse()?;
/// let system = SystemTime::from(moment);
/// #
/// # assert_eq!(Moment::from(system), moment);
/// # Ok(()) }
/// ```
///
/// #### Create a [`Moment`] from the current system time
///
/// ```rust
/// use std::time::SystemTime;
/// use ako::Moment;
///
/// let now: Moment = SystemTime::now().into();
/// ```
///
/// This is what [`Moment::now()`] does internally.
///
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Moment {
    pub(crate) secs: i64,
    pub(crate) nsec: u32,
}

// Constants
impl Moment {
    /// The maximum supported [`Moment`], `+1587287-03-17T15:30:07.999999999Z`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::Moment;
    ///
    /// assert_eq!(Moment::MAX.to_unix_seconds(), i64::MAX);
    /// # assert_eq!(Moment::MAX.to_string(), "+1587287-03-17T15:30:07.999999999Z");
    /// ```
    ///
    pub const MAX: Self = Self {
        secs: i64::MAX,
        nsec: 999_999_999,
    };

    /// The minimum (the largest negative) supported [`Moment`], `-1583348-10-16T08:29:52Z`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::Moment;
    ///
    /// assert_eq!(Moment::MIN.to_unix_seconds(), i64::MIN);
    /// # assert_eq!(Moment::MIN.to_string(), "-1583348-10-16T08:29:52Z");
    /// ```
    ///
    pub const MIN: Self = Self {
        secs: i64::MIN,
        nsec: 0,
    };
}

// Construction
impl Moment {
    /// Returns the moment corresponding to “now.”
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::Moment;
    ///
    /// // Current moment as reported by the system
    /// let now = Moment::now();
    /// # assert!(now.to_unix_seconds() >= 1727634133);
    /// ```
    ///
    #[cfg(feature = "std")]
    #[must_use]
    pub fn now() -> Self {
        std::time::SystemTime::now().into()
    }
}

// Conversion From
impl Moment {
    // This exists because From::from is not `const`
    /// Obtains the moment corresponding to the given [`Date`].
    #[must_use]
    pub(crate) const fn from_date<C: Calendar>(date: Date<C>) -> Self {
        Self {
            secs: (date.as_days_since_unix_epoch() as i64) * SECONDS_IN_DAY,
            nsec: 0,
        }
    }

    /// Creates a [`Moment`] from the given number of `seconds` and `nanoseconds`
    /// since the Unix epoch of January 1, 1970, at 00:00:00 UTC.
    ///
    /// Allows for an out-of-range `nanoseconds` value to be passed in. The
    /// `nanoseconds` will overflow into `seconds` to ensure that the
    /// stored sub-second nanoseconds are in the range 0 to 999,999,999.
    ///
    #[must_use]
    pub const fn from_unix(seconds: i64, nanoseconds: u32) -> Self {
        let mut nanoseconds = nanoseconds as i128;
        nanoseconds += seconds as i128 * 1_000_000_000;

        Self::from_unix_nanoseconds(nanoseconds)
    }

    /// Creates a [`Moment`] from the given number of `seconds`
    /// since the Unix epoch of January 1, 1970, at 00:00:00 UTC.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::Moment;
    ///
    /// // first appearance of the gregorian date represented by the
    /// // Unix timestamp to be in the timestamp
    /// let date_in_timestamp = Moment::from_unix_seconds(1_1973_10_17);
    /// assert_eq!(date_in_timestamp.to_string(), "1973-10-17T18:36:57Z");
    /// ```
    ///
    #[must_use]
    pub const fn from_unix_seconds(seconds: i64) -> Self {
        Self {
            secs: seconds,
            nsec: 0,
        }
    }

    /// Creates a [`Moment`] from the given number of `milliseconds`
    /// since the Unix epoch of January 1, 1970, at 00:00:00 UTC.
    #[must_use]
    pub const fn from_unix_milliseconds(milliseconds: i64) -> Self {
        Self::from_unix_nanoseconds(milliseconds as i128 * 1_000_000)
    }

    /// Creates a [`Moment`] from the given number of `microseconds`
    /// since the Unix epoch of January 1, 1970, at 00:00:00 UTC.
    #[must_use]
    pub const fn from_unix_microseconds(microseconds: i128) -> Self {
        Self::from_unix_nanoseconds(microseconds * 1_000)
    }

    /// Creates a [`Moment`] from the given number of `nanoseconds`
    /// since the Unix epoch of January 1, 1970, at 00:00:00 UTC.
    #[must_use]
    pub const fn from_unix_nanoseconds(nanoseconds: i128) -> Self {
        let secs = nanoseconds.div_euclid(1_000_000_000) as i64;
        let nsec = nanoseconds.rem_euclid(1_000_000_000) as u32;

        Self { secs, nsec }
    }

    /// Creates a [`Moment`] corresponding to the given [Julian day] (JD).
    ///
    /// The Julian day is the continuous count of days and fractions thereof
    /// from the beginning of the Julian period, where day 0 is Monday, January 1, 4713 BCE of the
    /// Julian calendar.
    ///
    /// [Julian day]: https://en.wikipedia.org/wiki/Julian_day
    ///
    #[cfg(feature = "astronomy")]
    pub fn from_julian_day(jd: f64) -> crate::Result<Self> {
        crate::astronomy::from_julian_day(jd)
    }

    /// Creates a [`Moment`] corresponding to the given [Julian day] (JD) in
    /// the Dynamical timescale (also known as [Ephemeris time]).
    ///
    /// [Julian day]: https://en.wikipedia.org/wiki/Julian_day
    /// [Ephemeris time]: https://en.wikipedia.org/wiki/Ephemeris_time
    ///
    #[cfg(feature = "astronomy")]
    pub fn from_julian_ephemeris_day(jde: f64) -> crate::Result<Self> {
        let mut moment = Self::from_julian_day(jde)?;

        // the difference (ΔT) between dynamic time (TD) and universal time (UT), in seconds
        let dt = crate::astronomy::delta_t(moment.to_julian_year());
        moment.secs -= dt as i64;

        Ok(moment)
    }
}

// Composition
impl Moment {
    /// Converts this moment to a [`DateTime`] projected to the ISO calendar, at the
    /// given time zone.
    ///
    #[must_use]
    pub(crate) fn at(self, tz: &TimeZone) -> DateTime<Iso> {
        DateTime::from_moment(Iso, self).at(tz)
    }

    /// Converts this moment to a [`DateTime`] projected on the given `calendar`.
    ///
    #[must_use]
    pub(crate) const fn on<C: Calendar>(self, calendar: C) -> DateTime<C> {
        DateTime::from_moment(calendar, self)
    }

    /// Gets this moment as a date projected to the given calendar.
    ///
    #[must_use]
    pub(crate) const fn as_date<C: Calendar>(self, calendar: C) -> Date<C> {
        Date::from_unix_timestamp(calendar, self.secs)
    }
}

// Conversion To
impl Moment {
    /// Gets the number of seconds and nanoseconds since the Unix epoch.
    /// Negative seconds represent moments before the Unix epoch.
    #[must_use]
    pub const fn to_unix(self) -> (i64, u32) {
        (self.secs, self.nsec)
    }

    /// Gets the number of seconds since the Unix epoch.
    /// Negative seconds represent moments before the Unix epoch.
    #[must_use]
    pub const fn to_unix_seconds(self) -> i64 {
        self.secs
    }

    /// Gets the number of milliseconds since the Unix epoch.
    #[must_use]
    pub const fn to_unix_milliseconds(self) -> i64 {
        self.to_unix_nanoseconds().div_euclid(1_000_000) as i64
    }

    /// Gets the number of microseconds since the Unix epoch.
    #[must_use]
    pub const fn to_unix_microseconds(self) -> i64 {
        self.to_unix_nanoseconds().div_euclid(1_000) as i64
    }

    /// Gets the number of nanoseconds since the Unix epoch.
    #[must_use]
    pub const fn to_unix_nanoseconds(self) -> i128 {
        ((self.secs as i128) * 1_000_000_000) + (self.nsec as i128)
    }

    /// Gets the [Julian day] (JD) for this moment.
    ///
    /// [Julian day]: https://en.wikipedia.org/wiki/Julian_day
    ///
    #[cfg(feature = "astronomy")]
    #[must_use]
    pub fn to_julian_day(self) -> f64 {
        crate::astronomy::to_julian_day(self)
    }

    /// Gets the [Julian year] (a) for this moment.
    ///
    /// In astronomy, a [Julian year] (a) is a unit of measurement of time defined
    /// as exactly 365.25 days of 86,400 seconds each. The [Julian year] does not
    /// correspond to years in any calendar.
    ///
    /// [Julian year]: https://en.wikipedia.org/wiki/Julian_year_(astronomy)
    ///
    #[cfg(feature = "astronomy")]
    #[must_use]
    pub fn to_julian_year(self) -> f64 {
        crate::astronomy::to_julian_year(self)
    }
}

impl Add<TimeInterval> for Moment {
    type Output = Self;

    fn add(self, rhs: TimeInterval) -> Self::Output {
        let nanoseconds = self
            .to_unix_nanoseconds()
            .checked_add(rhs.as_total_nanoseconds())
            .expect("overflow adding `TimeInterval` to `Moment`");

        Self::from_unix_nanoseconds(nanoseconds)
    }
}

impl Add<Moment> for TimeInterval {
    type Output = Moment;

    #[inline]
    fn add(self, rhs: Moment) -> Self::Output {
        rhs + self
    }
}

impl Sub<TimeInterval> for Moment {
    type Output = Self;

    fn sub(self, rhs: TimeInterval) -> Self::Output {
        let nanoseconds = self
            .to_unix_nanoseconds()
            .checked_sub(rhs.as_total_nanoseconds())
            .expect("overflow subtracting `TimeInterval` from `Moment`");

        Self::from_unix_nanoseconds(nanoseconds)
    }
}

impl Add<Duration> for Moment {
    type Output = Self;

    fn add(self, rhs: Duration) -> Self::Output {
        let nanoseconds = i128::try_from(rhs.as_nanos())
            .ok()
            .and_then(|rhs| self.to_unix_nanoseconds().checked_add(rhs))
            .expect("overflow adding `Duration` to `Moment`");

        Self::from_unix_nanoseconds(nanoseconds)
    }
}

impl Add<Moment> for Duration {
    type Output = Moment;

    #[inline]
    fn add(self, rhs: Moment) -> Self::Output {
        rhs + self
    }
}

impl Sub<Duration> for Moment {
    type Output = Self;

    fn sub(self, rhs: Duration) -> Self::Output {
        let nanoseconds = i128::try_from(rhs.as_nanos())
            .ok()
            .and_then(|rhs| self.to_unix_nanoseconds().checked_sub(rhs))
            .expect("overflow subtracting `Duration` from `Moment`");

        Self::from_unix_nanoseconds(nanoseconds)
    }
}

#[cfg(feature = "std")]
impl From<std::time::SystemTime> for Moment {
    fn from(time: std::time::SystemTime) -> Self {
        use std::time::SystemTime;

        let (secs, nsec) = time.duration_since(SystemTime::UNIX_EPOCH).map_or_else(
            |_| {
                let ts = SystemTime::UNIX_EPOCH
                    .duration_since(time)
                    .unwrap_or_default();

                (-(ts.as_secs() as i64), ts.subsec_nanos())
            },
            |ts| (ts.as_secs() as i64, ts.subsec_nanos()),
        );

        Self { secs, nsec }
    }
}

#[cfg(feature = "std")]
impl From<Moment> for std::time::SystemTime {
    fn from(moment: Moment) -> Self {
        let (secs, nsec) = moment.to_unix();
        let duration = Duration::new(secs.unsigned_abs(), nsec);

        if secs.is_negative() {
            Self::UNIX_EPOCH - duration
        } else {
            Self::UNIX_EPOCH + duration
        }
    }
}

impl<C: Calendar> From<Date<C>> for Moment {
    fn from(date: Date<C>) -> Self {
        Self::from_date(date)
    }
}

impl Display for Moment {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.pad(&self.format_rfc3339())
    }
}

impl Debug for Moment {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        <Self as Display>::fmt(self, f)
    }
}

impl FromStr for Moment {
    type Err = crate::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_rfc3339(s)
    }
}

impl AsMoment for Moment {
    fn as_moment(&self) -> Self {
        *self
    }
}

impl AsTime for Moment {
    fn as_time(&self) -> PlainTime {
        let (secs, nsec) = self.as_timestamp();
        PlainTime::from_unix_timestamp(secs, nsec)
    }

    fn as_timestamp(&self) -> (i64, u32) {
        self.to_unix()
    }
}

impl Sub<Self> for Moment {
    type Output = TimeInterval;

    fn sub(self, rhs: Self) -> Self::Output {
        // between flips the order, think of it like you write "end - start" but
        // you would say "between start and end"
        TimeInterval::between(rhs, self)
    }
}

#[cfg(test)]
mod tests {
    use core::time::Duration;

    use test_case::test_case;

    use crate::{AsMoment, DateTime, Moment};

    #[cfg(feature = "astronomy")]
    // From Astronomical Algorithms 2nd Edition, Chapter 7, Page 62
    #[test_case(2443259.9, "1977-04-26T09:35:59.999991953Z")]
    #[test_case(2451545.0, "2000-01-01T12:00:00Z")]
    #[test_case(2415020.5, "1900-01-01T00:00:00Z")]
    #[test_case(2299161.5, "1582-10-16T00:00:00Z")]
    #[test_case(2299160.5, "1582-10-15T00:00:00Z")]
    #[test_case(2299159.5, "1582-10-14T00:00:00Z")]
    #[test_case(2026871.8, "0837-04-14T07:12:00.000004023Z")]
    #[test_case(1355671.4, "-1001-08-07T21:35:59.999991953Z")]
    #[test_case(0.0, "-4713-11-24T12:00:00Z")]
    fn moment_from_julian_day(jd: f64, expected: &str) -> crate::Result<()> {
        let moment = Moment::from_julian_day(jd)?;

        assert_eq!(moment.format_rfc3339(), expected);
        assert_eq!(moment.to_julian_day(), jd);

        let dt = DateTime::parse_rfc3339(expected)?;

        assert_eq!(dt.as_moment(), moment);

        Ok(())
    }

    #[cfg(feature = "std")]
    #[test_case(-1727313985 ; "negative 1727313985")]
    #[test_case(0)]
    #[test_case(1727313985)]
    fn moment_from_system_time(timestamp: i64) {
        use std::time::SystemTime;

        let moment = Moment::from_unix_seconds(timestamp);
        let st = SystemTime::from(moment);
        let moment_2 = Moment::from(st);

        assert_eq!(moment_2, moment);
    }

    #[test_case(1727313985, 86_400, "2024-09-27T01:26:25Z")]
    #[test_case(1727313985, 18_000, "2024-09-26T06:26:25Z")]
    #[test_case(1727313985, 600, "2024-09-26T01:36:25Z")]
    fn moment_add_duration(timestamp: i64, seconds: u64, expected: &str) {
        let mut moment = Moment::from_unix_seconds(timestamp);
        moment = moment + Duration::from_secs(seconds);

        assert_eq!(moment.format_rfc3339(), expected);
    }

    #[test_case(1727313985, 86_400, "2024-09-25T01:26:25Z")]
    #[test_case(1727313985, 18_000, "2024-09-25T20:26:25Z")]
    #[test_case(1727313985, 600, "2024-09-26T01:16:25Z")]
    fn moment_sub_duration(timestamp: i64, seconds: u64, expected: &str) {
        let mut moment = Moment::from_unix_seconds(timestamp);
        moment = moment - Duration::from_secs(seconds);

        assert_eq!(moment.format_rfc3339(), expected);
    }

    #[test_case(1727313985, 1727480105, (1, 22, 8, 40))]
    fn moment_sub_moment(timestamp_start: i64, timestamp_end: i64, expected: (i64, i8, i8, i8)) {
        let moment_start = Moment::from_unix_seconds(timestamp_start);
        let moment_end = Moment::from_unix_seconds(timestamp_end);
        let ti = moment_end - moment_start;

        assert_eq!(ti.days(), expected.0);
        assert_eq!(ti.hours(), expected.1);
        assert_eq!(ti.minutes(), expected.2);
        assert_eq!(ti.seconds(), expected.3);
    }
}