jiff/timestamp.rs
1use core::time::Duration as UnsignedDuration;
2
3use jcore::Timestamp as JTimestamp;
4
5use crate::{
6 RoundMode, SignedDuration, Span, SpanRound, Unit,
7 duration::{Duration, SDuration},
8 error::{
9 Error, ErrorContext, timestamp::Error as E, unit::UnitConfigError,
10 },
11 fmt::{
12 self,
13 temporal::{self, DEFAULT_DATETIME_PARSER},
14 },
15 tz::{Offset, TimeZone},
16 util::{constant, round::Increment},
17 zoned::ZonedDateTime,
18};
19
20/// An instant in time represented as the number of nanoseconds since the Unix
21/// epoch.
22///
23/// A timestamp is always in the Unix timescale with a UTC offset of zero.
24///
25/// To obtain civil or "local" datetime units like year, month, day or hour, a
26/// timestamp needs to be combined with a [`TimeZone`] to create a
27/// [`ZonedDateTime`]. That can be done with [`Timestamp::in_tz`] or
28/// [`Timestamp::to_zoned_datetime`].
29///
30/// The integer count of nanoseconds since the Unix epoch is signed, where
31/// the Unix epoch is `1970-01-01 00:00:00Z`. A positive timestamp indicates
32/// a point in time after the Unix epoch. A negative timestamp indicates a
33/// point in time before the Unix epoch.
34///
35/// # Parsing and printing
36///
37/// The `Timestamp` type provides convenient trait implementations of
38/// [`std::str::FromStr`] and [`std::fmt::Display`]:
39///
40/// ```
41/// use jiff::Timestamp;
42///
43/// let ts: Timestamp = "2024-06-19 15:22:45-04".parse()?;
44/// assert_eq!(ts.to_string(), "2024-06-19T19:22:45Z");
45///
46/// # Ok::<(), Box<dyn std::error::Error>>(())
47/// ```
48///
49/// A `Timestamp` can also be parsed from something that _contains_ a
50/// timestamp, but with perhaps other data (such as a time zone):
51///
52/// ```
53/// use jiff::Timestamp;
54///
55/// let ts: Timestamp = "2024-06-19T15:22:45-04[America/New_York]".parse()?;
56/// assert_eq!(ts.to_string(), "2024-06-19T19:22:45Z");
57///
58/// # Ok::<(), Box<dyn std::error::Error>>(())
59/// ```
60///
61/// For more information on the specific format supported, see the
62/// [`fmt::temporal`](crate::fmt::temporal) module documentation.
63///
64/// # Default value
65///
66/// For convenience, this type implements the `Default` trait. Its default
67/// value corresponds to `1970-01-01T00:00:00.000000000`. That is, it is the
68/// Unix epoch. One can also access this value via the `Timestamp::UNIX_EPOCH`
69/// constant.
70///
71/// # Leap seconds
72///
73/// Jiff does not support leap seconds. Jiff behaves as if they don't exist.
74/// The only exception is that if one parses a timestamp with a second
75/// component of `60`, then it is automatically constrained to `59`:
76///
77/// ```
78/// use jiff::Timestamp;
79///
80/// let ts: Timestamp = "2016-12-31 23:59:60Z".parse()?;
81/// assert_eq!(ts.to_string(), "2016-12-31T23:59:59Z");
82///
83/// # Ok::<(), Box<dyn std::error::Error>>(())
84/// ```
85///
86/// # Comparisons
87///
88/// The `Timestamp` type provides both `Eq` and `Ord` trait implementations
89/// to facilitate easy comparisons. When a timestamp `ts1` occurs before a
90/// timestamp `ts2`, then `dt1 < dt2`. For example:
91///
92/// ```
93/// use jiff::Timestamp;
94///
95/// let ts1 = Timestamp::from_second(123_456_789)?;
96/// let ts2 = Timestamp::from_second(123_456_790)?;
97/// assert!(ts1 < ts2);
98///
99/// # Ok::<(), Box<dyn std::error::Error>>(())
100/// ```
101///
102/// # Arithmetic
103///
104/// This type provides routines for adding and subtracting spans of time, as
105/// well as computing the span of time between two `Timestamp` values.
106///
107/// For adding or subtracting spans of time, one can use any of the following
108/// routines:
109///
110/// * [`Timestamp::checked_add`] or [`Timestamp::checked_sub`] for checked
111/// arithmetic.
112/// * [`Timestamp::saturating_add`] or [`Timestamp::saturating_sub`] for
113/// saturating arithmetic.
114///
115/// Additionally, checked arithmetic is available via the `Add` and `Sub`
116/// trait implementations. When the result overflows, a panic occurs.
117///
118/// ```
119/// use jiff::{Timestamp, ToSpan};
120///
121/// let ts1: Timestamp = "2024-02-25T15:45Z".parse()?;
122/// let ts2 = ts1 - 24.hours();
123/// assert_eq!(ts2.to_string(), "2024-02-24T15:45:00Z");
124///
125/// # Ok::<(), Box<dyn std::error::Error>>(())
126/// ```
127///
128/// One can compute the span of time between two timestamps using either
129/// [`Timestamp::until`] or [`Timestamp::since`]. It's also possible to
130/// subtract two `Timestamp` values directly via a `Sub` trait implementation
131/// (which returns a `SignedDuration`):
132///
133/// ```
134/// use jiff::{SignedDuration, Timestamp};
135///
136/// let ts1: Timestamp = "2024-05-03 23:30:00.123Z".parse()?;
137/// let ts2: Timestamp = "2024-02-25 07Z".parse()?;
138/// assert_eq!(ts1 - ts2, SignedDuration::new(5_934_600, 123_000_000));
139///
140/// # Ok::<(), Box<dyn std::error::Error>>(())
141/// ```
142///
143/// The `until` and `since` APIs are polymorphic and allow re-balancing and
144/// rounding the span returned. For example, the default largest unit is
145/// seconds (as exemplified above), but we can ask for bigger units (up to
146/// hours):
147///
148/// ```
149/// use jiff::{Timestamp, ToSpan, Unit};
150///
151/// let ts1: Timestamp = "2024-05-03 23:30:00.123Z".parse()?;
152/// let ts2: Timestamp = "2024-02-25 07Z".parse()?;
153/// assert_eq!(
154/// // If you want to deal in units bigger than hours, then you'll have to
155/// // convert your timestamp to a [`ZonedDateTime`] first.
156/// ts1.since((Unit::Hour, ts2))?,
157/// 1648.hours().minutes(30).milliseconds(123).fieldwise(),
158/// );
159///
160/// # Ok::<(), Box<dyn std::error::Error>>(())
161/// ```
162///
163/// You can also round the span returned:
164///
165/// ```
166/// use jiff::{RoundMode, Timestamp, TimestampDifference, ToSpan, Unit};
167///
168/// let ts1: Timestamp = "2024-05-03 23:30:59.123Z".parse()?;
169/// let ts2: Timestamp = "2024-05-02 07Z".parse()?;
170/// assert_eq!(
171/// ts1.since(
172/// TimestampDifference::new(ts2)
173/// .smallest(Unit::Minute)
174/// .largest(Unit::Hour),
175/// )?,
176/// 40.hours().minutes(30).fieldwise(),
177/// );
178/// // `TimestampDifference` uses truncation as a rounding mode by default,
179/// // but you can set the rounding mode to break ties away from zero:
180/// assert_eq!(
181/// ts1.since(
182/// TimestampDifference::new(ts2)
183/// .smallest(Unit::Minute)
184/// .largest(Unit::Hour)
185/// .mode(RoundMode::HalfExpand),
186/// )?,
187/// // Rounds up to 31 minutes.
188/// 40.hours().minutes(31).fieldwise(),
189/// );
190///
191/// # Ok::<(), Box<dyn std::error::Error>>(())
192/// ```
193///
194/// # Rounding timestamps
195///
196/// A `Timestamp` can be rounded based on a [`TimestampRound`] configuration of
197/// smallest units, rounding increment and rounding mode. Here's an example
198/// showing how to round to the nearest third hour:
199///
200/// ```
201/// use jiff::{Timestamp, TimestampRound, Unit};
202///
203/// let ts: Timestamp = "2024-06-19 16:27:29.999999999Z".parse()?;
204/// assert_eq!(
205/// ts.round(TimestampRound::new().smallest(Unit::Hour).increment(3))?,
206/// "2024-06-19 15Z".parse::<Timestamp>()?,
207/// );
208/// // Or alternatively, make use of the `From<(Unit, i64)> for TimestampRound`
209/// // trait implementation:
210/// assert_eq!(
211/// ts.round((Unit::Hour, 3))?.to_string(),
212/// "2024-06-19T15:00:00Z",
213/// );
214///
215/// # Ok::<(), Box<dyn std::error::Error>>(())
216/// ```
217///
218/// See [`Timestamp::round`] for more details.
219///
220/// # An instant in time
221///
222/// Unlike a [`civil::DateTime`](crate::civil::DateTime), a `Timestamp`
223/// _always_ corresponds, unambiguously, to a precise instant in time (to
224/// nanosecond precision). This means that attaching a time zone to a timestamp
225/// is always unambiguous because there's never any question as to which
226/// instant it refers to. This is true even for gaps in civil time.
227///
228/// For example, in `America/New_York`, clocks were moved ahead one hour
229/// at clock time `2024-03-10 02:00:00`. That is, the 2 o'clock hour never
230/// appeared on clocks in the `America/New_York` region. Since parsing a
231/// timestamp always requires an offset, the time it refers to is unambiguous.
232/// We can see this by writing a clock time, `02:30`, that never existed but
233/// with two different offsets:
234///
235/// ```
236/// use jiff::Timestamp;
237///
238/// // All we're doing here is attaching an offset to a civil datetime.
239/// // There is no time zone information here, and thus there is no
240/// // accounting for ambiguity due to daylight saving time transitions.
241/// let before_hour_jump: Timestamp = "2024-03-10 02:30-04".parse()?;
242/// let after_hour_jump: Timestamp = "2024-03-10 02:30-05".parse()?;
243/// // This shows the instant in time in UTC.
244/// assert_eq!(before_hour_jump.to_string(), "2024-03-10T06:30:00Z");
245/// assert_eq!(after_hour_jump.to_string(), "2024-03-10T07:30:00Z");
246///
247/// // Now let's attach each instant to an `America/New_York` time zone.
248/// let zdt_before = before_hour_jump.in_tz("America/New_York")?;
249/// let zdt_after = after_hour_jump.in_tz("America/New_York")?;
250/// // And now we can see that even though the original instant refers to
251/// // the 2 o'clock hour, since that hour never existed on the clocks in
252/// // `America/New_York`, an instant with a time zone correctly adjusts.
253/// assert_eq!(
254/// zdt_before.to_string(),
255/// "2024-03-10T01:30:00-05:00[America/New_York]",
256/// );
257/// assert_eq!(
258/// zdt_after.to_string(),
259/// "2024-03-10T03:30:00-04:00[America/New_York]",
260/// );
261///
262/// # Ok::<(), Box<dyn std::error::Error>>(())
263/// ```
264///
265/// In the example above, there is never a step that is incorrect or has an
266/// alternative answer. Every step is unambiguous because we never involve
267/// any [`civil`](crate::civil) datetimes.
268///
269/// But note that if the datetime string you're parsing from lacks an offset,
270/// then it *could* be ambiguous even if a time zone is specified. In this
271/// case, parsing will always fail:
272///
273/// ```
274/// use jiff::Timestamp;
275///
276/// let result = "2024-06-30 08:30[America/New_York]".parse::<Timestamp>();
277/// assert_eq!(
278/// result.unwrap_err().to_string(),
279/// "failed to find offset component, \
280/// which is required for parsing a timestamp",
281/// );
282/// ```
283///
284/// # Converting a civil datetime to a timestamp
285///
286/// Sometimes you want to convert the "time on the clock" to a precise instant
287/// in time. One way to do this was demonstrated in the previous section, but
288/// it only works if you know your current time zone offset:
289///
290/// ```
291/// use jiff::Timestamp;
292///
293/// let ts: Timestamp = "2024-06-30 08:36-04".parse()?;
294/// assert_eq!(ts.to_string(), "2024-06-30T12:36:00Z");
295///
296/// # Ok::<(), Box<dyn std::error::Error>>(())
297/// ```
298///
299/// The above happened to be the precise instant in time I wrote the example.
300/// Since I happened to know the offset, this worked okay. But what if I
301/// didn't? We could instead construct a civil datetime and attach a time zone
302/// to it. This will create a [`ZonedDateTime`] value, from which we can access
303/// the timestamp:
304///
305/// ```
306/// use jiff::civil::date;
307///
308/// let clock = date(2024, 6, 30).at(8, 36, 0, 0).in_tz("America/New_York")?;
309/// assert_eq!(clock.timestamp().to_string(), "2024-06-30T12:36:00Z");
310///
311/// # Ok::<(), Box<dyn std::error::Error>>(())
312/// ```
313#[derive(Clone, Copy)]
314#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
315pub struct Timestamp {
316 dur: JTimestamp,
317}
318
319impl Timestamp {
320 /// The minimum representable timestamp.
321 ///
322 /// The minimum is chosen such that it can be combined with
323 /// any legal [`Offset`](crate::tz::Offset) and turned into a
324 /// [`civil::DateTime`](crate::civil::DateTime).
325 ///
326 /// # Example
327 ///
328 /// ```
329 /// use jiff::{civil::date, tz::Offset, Timestamp};
330 ///
331 /// let dt = Offset::MIN.to_datetime(Timestamp::MIN);
332 /// assert_eq!(dt, date(-9999, 1, 1).at(0, 0, 0, 0));
333 /// ```
334 pub const MIN: Timestamp = Timestamp { dur: JTimestamp::MIN };
335
336 /// The maximum representable timestamp.
337 ///
338 /// The maximum is chosen such that it can be combined with
339 /// any legal [`Offset`](crate::tz::Offset) and turned into a
340 /// [`civil::DateTime`](crate::civil::DateTime).
341 ///
342 /// # Example
343 ///
344 /// ```
345 /// use jiff::{civil::date, tz::Offset, Timestamp};
346 ///
347 /// let dt = Offset::MAX.to_datetime(Timestamp::MAX);
348 /// assert_eq!(dt, date(9999, 12, 31).at(23, 59, 59, 999_999_999));
349 /// ```
350 pub const MAX: Timestamp = Timestamp { dur: JTimestamp::MAX };
351
352 /// The Unix epoch represented as a timestamp.
353 ///
354 /// The Unix epoch corresponds to the instant at `1970-01-01T00:00:00Z`.
355 /// As a timestamp, it corresponds to `0` nanoseconds.
356 ///
357 /// A timestamp is positive if and only if it is greater than the Unix
358 /// epoch. A timestamp is negative if and only if it is less than the Unix
359 /// epoch.
360 pub const UNIX_EPOCH: Timestamp =
361 Timestamp { dur: JTimestamp::UNIX_EPOCH };
362
363 /// Returns the current system time as a timestamp.
364 ///
365 /// # Panics
366 ///
367 /// This panics if the system clock is set to a time value outside of the
368 /// range `-009999-01-01T00:00:00Z..=9999-12-31T11:59:59.999999999Z`. The
369 /// justification here is that it is reasonable to expect the system clock
370 /// to be set to a somewhat sane, if imprecise, value.
371 ///
372 /// If you want to get the current Unix time fallibly, use
373 /// [`Timestamp::try_from`] with a `std::time::SystemTime` as input.
374 ///
375 /// This may also panic when `SystemTime::now()` itself panics. The most
376 /// common context in which this happens is on the `wasm32-unknown-unknown`
377 /// target. If you're using that target in the context of the web (for
378 /// example, via `wasm-pack`), and you're an application, then you should
379 /// enable Jiff's `js` feature. This will automatically instruct Jiff in
380 /// this very specific circumstance to execute JavaScript code to determine
381 /// the current time from the web browser.
382 ///
383 /// # Example
384 ///
385 /// ```
386 /// use jiff::Timestamp;
387 ///
388 /// assert!(Timestamp::now() > Timestamp::UNIX_EPOCH);
389 /// ```
390 #[cfg(feature = "std")]
391 pub fn now() -> Timestamp {
392 Timestamp::try_from(crate::now::system_time())
393 .expect("system time is valid")
394 }
395
396 /// Creates a new instant in time represented as a timestamp.
397 ///
398 /// While a timestamp is logically a count of nanoseconds since the Unix
399 /// epoch, this constructor provides a convenience way of constructing
400 /// the timestamp from two components: seconds and fractional seconds
401 /// expressed as nanoseconds.
402 ///
403 /// The signs of `second` and `nanosecond` need not be the same.
404 ///
405 /// # Errors
406 ///
407 /// This returns an error if the given components would correspond to
408 /// an instant outside the supported range. Also, `nanosecond` is limited
409 /// to the range `-999,999,999..=999,999,999`.
410 ///
411 /// # Example
412 ///
413 /// This example shows the instant in time 123,456,789 seconds after the
414 /// Unix epoch:
415 ///
416 /// ```
417 /// use jiff::Timestamp;
418 ///
419 /// assert_eq!(
420 /// Timestamp::new(123_456_789, 0)?.to_string(),
421 /// "1973-11-29T21:33:09Z",
422 /// );
423 ///
424 /// # Ok::<(), Box<dyn std::error::Error>>(())
425 /// ```
426 ///
427 /// # Example: normalized sign
428 ///
429 /// This example shows how `second` and `nanosecond` are resolved when
430 /// their signs differ.
431 ///
432 /// ```
433 /// use jiff::Timestamp;
434 ///
435 /// let ts = Timestamp::new(2, -999_999_999)?;
436 /// assert_eq!(ts.as_second(), 1);
437 /// assert_eq!(ts.subsec_nanosecond(), 1);
438 ///
439 /// let ts = Timestamp::new(-2, 999_999_999)?;
440 /// assert_eq!(ts.as_second(), -1);
441 /// assert_eq!(ts.subsec_nanosecond(), -1);
442 ///
443 /// # Ok::<(), Box<dyn std::error::Error>>(())
444 /// ```
445 ///
446 /// # Example: limits
447 ///
448 /// The minimum timestamp has nanoseconds set to zero, while the maximum
449 /// timestamp has nanoseconds set to `999,999,999`:
450 ///
451 /// ```
452 /// use jiff::Timestamp;
453 ///
454 /// assert_eq!(Timestamp::MIN.subsec_nanosecond(), 0);
455 /// assert_eq!(Timestamp::MAX.subsec_nanosecond(), 999_999_999);
456 /// ```
457 ///
458 /// As a consequence, nanoseconds cannot be negative when a timestamp has
459 /// minimal seconds:
460 ///
461 /// ```
462 /// use jiff::Timestamp;
463 ///
464 /// assert!(Timestamp::new(Timestamp::MIN.as_second(), -1).is_err());
465 /// // But they can be positive!
466 /// let one_ns_more = Timestamp::new(Timestamp::MIN.as_second(), 1)?;
467 /// assert_eq!(
468 /// one_ns_more.to_string(),
469 /// "-009999-01-02T01:59:59.000000001Z",
470 /// );
471 /// // Or, when combined with a minimal offset:
472 /// assert_eq!(
473 /// jiff::tz::Offset::MIN.to_datetime(one_ns_more).to_string(),
474 /// "-009999-01-01T00:00:00.000000001",
475 /// );
476 ///
477 /// # Ok::<(), Box<dyn std::error::Error>>(())
478 /// ```
479 #[inline]
480 pub fn new(second: i64, nanosecond: i32) -> Result<Timestamp, Error> {
481 let dur =
482 JTimestamp::new(second, nanosecond).map_err(Error::jcore_range)?;
483 Ok(Timestamp { dur })
484 }
485
486 /// Creates a new `Timestamp` value in a `const` context.
487 ///
488 /// # Panics
489 ///
490 /// This routine panics when [`Timestamp::new`] would return an error.
491 /// That is, when the given components would correspond to
492 /// an instant outside the supported range. Also, `nanosecond` is limited
493 /// to the range `-999,999,999..=999,999,999`.
494 ///
495 /// # Example
496 ///
497 /// This example shows the instant in time 123,456,789 seconds after the
498 /// Unix epoch:
499 ///
500 /// ```
501 /// use jiff::Timestamp;
502 ///
503 /// assert_eq!(
504 /// Timestamp::constant(123_456_789, 0).to_string(),
505 /// "1973-11-29T21:33:09Z",
506 /// );
507 /// ```
508 #[inline]
509 pub const fn constant(second: i64, nanosecond: i32) -> Timestamp {
510 let dur = constant::unwrapr!(
511 JTimestamp::new(second, nanosecond),
512 "invalid timestamp"
513 );
514 Timestamp { dur }
515 }
516
517 /// Creates a new instant in time from the number of seconds elapsed since
518 /// the Unix epoch.
519 ///
520 /// When `second` is negative, it corresponds to an instant in time before
521 /// the Unix epoch. A smaller number corresponds to an instant in time
522 /// further into the past.
523 ///
524 /// # Errors
525 ///
526 /// This returns an error if the given second corresponds to a timestamp
527 /// outside of the [`Timestamp::MIN`] and [`Timestamp::MAX`] boundaries.
528 ///
529 /// It is a semver guarantee that the only way for this to return an error
530 /// is if the given value is out of range. That is, when it is less than
531 /// `Timestamp::MIN` or greater than `Timestamp::MAX`.
532 ///
533 /// # Example
534 ///
535 /// This example shows the instants in time 1 second immediately after and
536 /// before the Unix epoch:
537 ///
538 /// ```
539 /// use jiff::Timestamp;
540 ///
541 /// assert_eq!(
542 /// Timestamp::from_second(1)?.to_string(),
543 /// "1970-01-01T00:00:01Z",
544 /// );
545 /// assert_eq!(
546 /// Timestamp::from_second(-1)?.to_string(),
547 /// "1969-12-31T23:59:59Z",
548 /// );
549 ///
550 /// # Ok::<(), Box<dyn std::error::Error>>(())
551 /// ```
552 ///
553 /// # Example: saturating construction
554 ///
555 /// If you need a way to build a `Timestamp` value that saturates to
556 /// the minimum and maximum values supported by Jiff, then this is
557 /// guaranteed to work:
558 ///
559 /// ```
560 /// use jiff::Timestamp;
561 ///
562 /// fn from_second_saturating(seconds: i64) -> Timestamp {
563 /// Timestamp::from_second(seconds).unwrap_or_else(|_| {
564 /// if seconds < 0 {
565 /// Timestamp::MIN
566 /// } else {
567 /// Timestamp::MAX
568 /// }
569 /// })
570 /// }
571 ///
572 /// assert_eq!(from_second_saturating(0), Timestamp::UNIX_EPOCH);
573 /// assert_eq!(
574 /// from_second_saturating(-999999999999999999),
575 /// Timestamp::MIN
576 /// );
577 /// assert_eq!(
578 /// from_second_saturating(999999999999999999),
579 /// Timestamp::MAX
580 /// );
581 /// ```
582 #[inline]
583 pub fn from_second(second: i64) -> Result<Timestamp, Error> {
584 JTimestamp::from_second(second)
585 .map(|dur| Timestamp { dur })
586 .map_err(Error::jcore_range)
587 }
588
589 /// Creates a new instant in time from the number of milliseconds elapsed
590 /// since the Unix epoch.
591 ///
592 /// When `millisecond` is negative, it corresponds to an instant in time
593 /// before the Unix epoch. A smaller number corresponds to an instant in
594 /// time further into the past.
595 ///
596 /// # Errors
597 ///
598 /// This returns an error if the given millisecond corresponds to a
599 /// timestamp outside of the [`Timestamp::MIN`] and [`Timestamp::MAX`]
600 /// boundaries.
601 ///
602 /// It is a semver guarantee that the only way for this to return an error
603 /// is if the given value is out of range. That is, when it is less than
604 /// `Timestamp::MIN` or greater than `Timestamp::MAX`.
605 ///
606 /// # Example
607 ///
608 /// This example shows the instants in time 1 millisecond immediately after
609 /// and before the Unix epoch:
610 ///
611 /// ```
612 /// use jiff::Timestamp;
613 ///
614 /// assert_eq!(
615 /// Timestamp::from_millisecond(1)?.to_string(),
616 /// "1970-01-01T00:00:00.001Z",
617 /// );
618 /// assert_eq!(
619 /// Timestamp::from_millisecond(-1)?.to_string(),
620 /// "1969-12-31T23:59:59.999Z",
621 /// );
622 ///
623 /// # Ok::<(), Box<dyn std::error::Error>>(())
624 /// ```
625 ///
626 /// # Example: saturating construction
627 ///
628 /// If you need a way to build a `Timestamp` value that saturates to
629 /// the minimum and maximum values supported by Jiff, then this is
630 /// guaranteed to work:
631 ///
632 /// ```
633 /// use jiff::Timestamp;
634 ///
635 /// fn from_millisecond_saturating(millis: i64) -> Timestamp {
636 /// Timestamp::from_millisecond(millis).unwrap_or_else(|_| {
637 /// if millis < 0 {
638 /// Timestamp::MIN
639 /// } else {
640 /// Timestamp::MAX
641 /// }
642 /// })
643 /// }
644 ///
645 /// assert_eq!(from_millisecond_saturating(0), Timestamp::UNIX_EPOCH);
646 /// assert_eq!(
647 /// from_millisecond_saturating(-999999999999999999),
648 /// Timestamp::MIN
649 /// );
650 /// assert_eq!(
651 /// from_millisecond_saturating(999999999999999999),
652 /// Timestamp::MAX
653 /// );
654 /// ```
655 #[inline]
656 pub fn from_millisecond(millisecond: i64) -> Result<Timestamp, Error> {
657 JTimestamp::from_millisecond(millisecond)
658 .map(|dur| Timestamp { dur })
659 .map_err(Error::jcore_range)
660 }
661
662 /// Creates a new instant in time from the number of microseconds elapsed
663 /// since the Unix epoch.
664 ///
665 /// When `microsecond` is negative, it corresponds to an instant in time
666 /// before the Unix epoch. A smaller number corresponds to an instant in
667 /// time further into the past.
668 ///
669 /// # Errors
670 ///
671 /// This returns an error if the given microsecond corresponds to a
672 /// timestamp outside of the [`Timestamp::MIN`] and [`Timestamp::MAX`]
673 /// boundaries.
674 ///
675 /// It is a semver guarantee that the only way for this to return an error
676 /// is if the given value is out of range. That is, when it is less than
677 /// `Timestamp::MIN` or greater than `Timestamp::MAX`.
678 ///
679 /// # Example
680 ///
681 /// This example shows the instants in time 1 microsecond immediately after
682 /// and before the Unix epoch:
683 ///
684 /// ```
685 /// use jiff::Timestamp;
686 ///
687 /// assert_eq!(
688 /// Timestamp::from_microsecond(1)?.to_string(),
689 /// "1970-01-01T00:00:00.000001Z",
690 /// );
691 /// assert_eq!(
692 /// Timestamp::from_microsecond(-1)?.to_string(),
693 /// "1969-12-31T23:59:59.999999Z",
694 /// );
695 ///
696 /// # Ok::<(), Box<dyn std::error::Error>>(())
697 /// ```
698 ///
699 /// # Example: saturating construction
700 ///
701 /// If you need a way to build a `Timestamp` value that saturates to
702 /// the minimum and maximum values supported by Jiff, then this is
703 /// guaranteed to work:
704 ///
705 /// ```
706 /// use jiff::Timestamp;
707 ///
708 /// fn from_microsecond_saturating(micros: i64) -> Timestamp {
709 /// Timestamp::from_microsecond(micros).unwrap_or_else(|_| {
710 /// if micros < 0 {
711 /// Timestamp::MIN
712 /// } else {
713 /// Timestamp::MAX
714 /// }
715 /// })
716 /// }
717 ///
718 /// assert_eq!(from_microsecond_saturating(0), Timestamp::UNIX_EPOCH);
719 /// assert_eq!(
720 /// from_microsecond_saturating(-999999999999999999),
721 /// Timestamp::MIN
722 /// );
723 /// assert_eq!(
724 /// from_microsecond_saturating(999999999999999999),
725 /// Timestamp::MAX
726 /// );
727 /// ```
728 #[inline]
729 pub fn from_microsecond(microsecond: i64) -> Result<Timestamp, Error> {
730 JTimestamp::from_microsecond(microsecond)
731 .map(|dur| Timestamp { dur })
732 .map_err(Error::jcore_range)
733 }
734
735 /// Creates a new instant in time from the number of nanoseconds elapsed
736 /// since the Unix epoch.
737 ///
738 /// When `nanosecond` is negative, it corresponds to an instant in time
739 /// before the Unix epoch. A smaller number corresponds to an instant in
740 /// time further into the past.
741 ///
742 /// # Errors
743 ///
744 /// This returns an error if the given nanosecond corresponds to a
745 /// timestamp outside of the [`Timestamp::MIN`] and [`Timestamp::MAX`]
746 /// boundaries.
747 ///
748 /// It is a semver guarantee that the only way for this to return an error
749 /// is if the given value is out of range. That is, when it is less than
750 /// `Timestamp::MIN` or greater than `Timestamp::MAX`.
751 ///
752 /// # Example
753 ///
754 /// This example shows the instants in time 1 nanosecond immediately after
755 /// and before the Unix epoch:
756 ///
757 /// ```
758 /// use jiff::Timestamp;
759 ///
760 /// assert_eq!(
761 /// Timestamp::from_nanosecond(1)?.to_string(),
762 /// "1970-01-01T00:00:00.000000001Z",
763 /// );
764 /// assert_eq!(
765 /// Timestamp::from_nanosecond(-1)?.to_string(),
766 /// "1969-12-31T23:59:59.999999999Z",
767 /// );
768 ///
769 /// # Ok::<(), Box<dyn std::error::Error>>(())
770 /// ```
771 ///
772 /// # Example: saturating construction
773 ///
774 /// If you need a way to build a `Timestamp` value that saturates to
775 /// the minimum and maximum values supported by Jiff, then this is
776 /// guaranteed to work:
777 ///
778 /// ```
779 /// use jiff::Timestamp;
780 ///
781 /// fn from_nanosecond_saturating(nanos: i128) -> Timestamp {
782 /// Timestamp::from_nanosecond(nanos).unwrap_or_else(|_| {
783 /// if nanos < 0 {
784 /// Timestamp::MIN
785 /// } else {
786 /// Timestamp::MAX
787 /// }
788 /// })
789 /// }
790 ///
791 /// assert_eq!(from_nanosecond_saturating(0), Timestamp::UNIX_EPOCH);
792 /// assert_eq!(
793 /// from_nanosecond_saturating(-9999999999999999999999999999999999),
794 /// Timestamp::MIN
795 /// );
796 /// assert_eq!(
797 /// from_nanosecond_saturating(9999999999999999999999999999999999),
798 /// Timestamp::MAX
799 /// );
800 /// ```
801 #[inline]
802 pub fn from_nanosecond(nanosecond: i128) -> Result<Timestamp, Error> {
803 JTimestamp::from_nanosecond(nanosecond)
804 .map(|dur| Timestamp { dur })
805 .map_err(Error::jcore_range)
806 }
807
808 /// Creates a new timestamp from a `Duration` with the given sign since the
809 /// Unix epoch.
810 ///
811 /// Positive durations result in a timestamp after the Unix epoch. Negative
812 /// durations result in a timestamp before the Unix epoch.
813 ///
814 /// # Errors
815 ///
816 /// This returns an error if the given duration corresponds to a timestamp
817 /// outside of the [`Timestamp::MIN`] and [`Timestamp::MAX`] boundaries.
818 ///
819 /// It is a semver guarantee that the only way for this to return an error
820 /// is if the given value is out of range. That is, when it is less than
821 /// `Timestamp::MIN` or greater than `Timestamp::MAX`.
822 ///
823 /// # Example
824 ///
825 /// How one might construct a `Timestamp` from a `SystemTime`:
826 ///
827 /// ```
828 /// use std::time::SystemTime;
829 /// use jiff::{SignedDuration, Timestamp};
830 ///
831 /// let unix_epoch = SystemTime::UNIX_EPOCH;
832 /// let now = SystemTime::now();
833 /// let duration = SignedDuration::system_until(unix_epoch, now)?;
834 /// let ts = Timestamp::from_duration(duration)?;
835 /// assert!(ts > Timestamp::UNIX_EPOCH);
836 ///
837 /// # Ok::<(), Box<dyn std::error::Error>>(())
838 /// ```
839 ///
840 /// Of course, one should just use [`Timestamp::try_from`] for this
841 /// instead. Indeed, the above example is copied almost exactly from the
842 /// `TryFrom` implementation.
843 ///
844 /// # Example: out of bounds
845 ///
846 /// This example shows how some of the boundary conditions are dealt with.
847 ///
848 /// ```
849 /// use jiff::{SignedDuration, Timestamp};
850 ///
851 /// // OK, we get the minimum timestamp supported by Jiff:
852 /// let duration = SignedDuration::new(-377705023201, 0);
853 /// let ts = Timestamp::from_duration(duration)?;
854 /// assert_eq!(ts, Timestamp::MIN);
855 ///
856 /// // We use the minimum number of seconds, but even subtracting
857 /// // one more nanosecond after it will result in an error.
858 /// let duration = SignedDuration::new(-377705023201, -1);
859 /// assert_eq!(
860 /// Timestamp::from_duration(duration).unwrap_err().to_string(),
861 /// "parameter 'Unix timestamp seconds' is not in \
862 /// the required range of -377705023201..=253402207200",
863 /// );
864 ///
865 /// # Ok::<(), Box<dyn std::error::Error>>(())
866 /// ```
867 ///
868 /// # Example: saturating construction
869 ///
870 /// If you need a way to build a `Timestamp` value that saturates to
871 /// the minimum and maximum values supported by Jiff, then this is
872 /// guaranteed to work:
873 ///
874 /// ```
875 /// use jiff::{SignedDuration, Timestamp};
876 ///
877 /// fn from_duration_saturating(dur: SignedDuration) -> Timestamp {
878 /// Timestamp::from_duration(dur).unwrap_or_else(|_| {
879 /// if dur.is_negative() {
880 /// Timestamp::MIN
881 /// } else {
882 /// Timestamp::MAX
883 /// }
884 /// })
885 /// }
886 ///
887 /// assert_eq!(
888 /// from_duration_saturating(SignedDuration::ZERO),
889 /// Timestamp::UNIX_EPOCH,
890 /// );
891 /// assert_eq!(
892 /// from_duration_saturating(SignedDuration::from_secs(-999999999999)),
893 /// Timestamp::MIN
894 /// );
895 /// assert_eq!(
896 /// from_duration_saturating(SignedDuration::from_secs(999999999999)),
897 /// Timestamp::MAX
898 /// );
899 /// ```
900 #[inline]
901 pub fn from_duration(
902 duration: SignedDuration,
903 ) -> Result<Timestamp, Error> {
904 // N.B. We could do less work here since we know the signed duration
905 // is well formed (i.e., `|nanos| < 1 second` is always true).
906 Timestamp::new(duration.as_secs(), duration.subsec_nanos())
907 }
908
909 /// Returns this timestamp as a number of seconds since the Unix epoch.
910 ///
911 /// This only returns the number of whole seconds. That is, if there are
912 /// any fractional seconds in this timestamp, then they are truncated.
913 ///
914 /// # Example
915 ///
916 /// ```
917 /// use jiff::Timestamp;
918 ///
919 /// let ts = Timestamp::new(5, 123_456_789)?;
920 /// assert_eq!(ts.as_second(), 5);
921 /// let ts = Timestamp::new(5, 999_999_999)?;
922 /// assert_eq!(ts.as_second(), 5);
923 ///
924 /// let ts = Timestamp::new(-5, -123_456_789)?;
925 /// assert_eq!(ts.as_second(), -5);
926 /// let ts = Timestamp::new(-5, -999_999_999)?;
927 /// assert_eq!(ts.as_second(), -5);
928 ///
929 /// # Ok::<(), Box<dyn std::error::Error>>(())
930 /// ```
931 #[inline]
932 pub fn as_second(self) -> i64 {
933 self.dur.as_second()
934 }
935
936 /// Returns this timestamp as a number of milliseconds since the Unix
937 /// epoch.
938 ///
939 /// This only returns the number of whole milliseconds. That is, if there
940 /// are any fractional milliseconds in this timestamp, then they are
941 /// truncated.
942 ///
943 /// # Example
944 ///
945 /// ```
946 /// use jiff::Timestamp;
947 ///
948 /// let ts = Timestamp::new(5, 123_456_789)?;
949 /// assert_eq!(ts.as_millisecond(), 5_123);
950 /// let ts = Timestamp::new(5, 999_999_999)?;
951 /// assert_eq!(ts.as_millisecond(), 5_999);
952 ///
953 /// let ts = Timestamp::new(-5, -123_456_789)?;
954 /// assert_eq!(ts.as_millisecond(), -5_123);
955 /// let ts = Timestamp::new(-5, -999_999_999)?;
956 /// assert_eq!(ts.as_millisecond(), -5_999);
957 ///
958 /// # Ok::<(), Box<dyn std::error::Error>>(())
959 /// ```
960 #[inline]
961 pub fn as_millisecond(self) -> i64 {
962 self.dur.as_millisecond()
963 }
964
965 /// Returns this timestamp as a number of microseconds since the Unix
966 /// epoch.
967 ///
968 /// This only returns the number of whole microseconds. That is, if there
969 /// are any fractional microseconds in this timestamp, then they are
970 /// truncated.
971 ///
972 /// # Example
973 ///
974 /// ```
975 /// use jiff::Timestamp;
976 ///
977 /// let ts = Timestamp::new(5, 123_456_789)?;
978 /// assert_eq!(ts.as_microsecond(), 5_123_456);
979 /// let ts = Timestamp::new(5, 999_999_999)?;
980 /// assert_eq!(ts.as_microsecond(), 5_999_999);
981 ///
982 /// let ts = Timestamp::new(-5, -123_456_789)?;
983 /// assert_eq!(ts.as_microsecond(), -5_123_456);
984 /// let ts = Timestamp::new(-5, -999_999_999)?;
985 /// assert_eq!(ts.as_microsecond(), -5_999_999);
986 ///
987 /// # Ok::<(), Box<dyn std::error::Error>>(())
988 /// ```
989 #[inline]
990 pub fn as_microsecond(self) -> i64 {
991 self.dur.as_microsecond()
992 }
993
994 /// Returns this timestamp as a number of nanoseconds since the Unix
995 /// epoch.
996 ///
997 /// Since a `Timestamp` has a nanosecond precision, the nanoseconds
998 /// returned here represent this timestamp losslessly. That is, the
999 /// nanoseconds returned can be used with [`Timestamp::from_nanosecond`] to
1000 /// create an identical timestamp with no loss of precision.
1001 ///
1002 /// # Example
1003 ///
1004 /// ```
1005 /// use jiff::Timestamp;
1006 ///
1007 /// let ts = Timestamp::new(5, 123_456_789)?;
1008 /// assert_eq!(ts.as_nanosecond(), 5_123_456_789);
1009 /// let ts = Timestamp::new(5, 999_999_999)?;
1010 /// assert_eq!(ts.as_nanosecond(), 5_999_999_999);
1011 ///
1012 /// let ts = Timestamp::new(-5, -123_456_789)?;
1013 /// assert_eq!(ts.as_nanosecond(), -5_123_456_789);
1014 /// let ts = Timestamp::new(-5, -999_999_999)?;
1015 /// assert_eq!(ts.as_nanosecond(), -5_999_999_999);
1016 ///
1017 /// # Ok::<(), Box<dyn std::error::Error>>(())
1018 /// ```
1019 #[inline]
1020 pub fn as_nanosecond(self) -> i128 {
1021 self.dur.as_nanosecond()
1022 }
1023
1024 /// Returns the fractional second component of this timestamp in units
1025 /// of milliseconds.
1026 ///
1027 /// It is guaranteed that this will never return a value that is greater
1028 /// than 1 second (or less than -1 second).
1029 ///
1030 /// This only returns the number of whole milliseconds. That is, if there
1031 /// are any fractional milliseconds in this timestamp, then they are
1032 /// truncated.
1033 ///
1034 /// # Example
1035 ///
1036 /// ```
1037 /// use jiff::Timestamp;
1038 ///
1039 /// let ts = Timestamp::new(5, 123_456_789)?;
1040 /// assert_eq!(ts.subsec_millisecond(), 123);
1041 /// let ts = Timestamp::new(5, 999_999_999)?;
1042 /// assert_eq!(ts.subsec_millisecond(), 999);
1043 ///
1044 /// let ts = Timestamp::new(-5, -123_456_789)?;
1045 /// assert_eq!(ts.subsec_millisecond(), -123);
1046 /// let ts = Timestamp::new(-5, -999_999_999)?;
1047 /// assert_eq!(ts.subsec_millisecond(), -999);
1048 ///
1049 /// # Ok::<(), Box<dyn std::error::Error>>(())
1050 /// ```
1051 #[inline]
1052 pub fn subsec_millisecond(self) -> i32 {
1053 self.dur.subsec_millisecond()
1054 }
1055
1056 /// Returns the fractional second component of this timestamp in units of
1057 /// microseconds.
1058 ///
1059 /// It is guaranteed that this will never return a value that is greater
1060 /// than 1 second (or less than -1 second).
1061 ///
1062 /// This only returns the number of whole microseconds. That is, if there
1063 /// are any fractional microseconds in this timestamp, then they are
1064 /// truncated.
1065 ///
1066 /// # Example
1067 ///
1068 /// ```
1069 /// use jiff::Timestamp;
1070 ///
1071 /// let ts = Timestamp::new(5, 123_456_789)?;
1072 /// assert_eq!(ts.subsec_microsecond(), 123_456);
1073 /// let ts = Timestamp::new(5, 999_999_999)?;
1074 /// assert_eq!(ts.subsec_microsecond(), 999_999);
1075 ///
1076 /// let ts = Timestamp::new(-5, -123_456_789)?;
1077 /// assert_eq!(ts.subsec_microsecond(), -123_456);
1078 /// let ts = Timestamp::new(-5, -999_999_999)?;
1079 /// assert_eq!(ts.subsec_microsecond(), -999_999);
1080 ///
1081 /// # Ok::<(), Box<dyn std::error::Error>>(())
1082 /// ```
1083 #[inline]
1084 pub fn subsec_microsecond(self) -> i32 {
1085 self.dur.subsec_microsecond()
1086 }
1087
1088 /// Returns the fractional second component of this timestamp in units of
1089 /// nanoseconds.
1090 ///
1091 /// It is guaranteed that this will never return a value that is greater
1092 /// than 1 second (or less than -1 second).
1093 ///
1094 /// # Example
1095 ///
1096 /// ```
1097 /// use jiff::Timestamp;
1098 ///
1099 /// let ts = Timestamp::new(5, 123_456_789)?;
1100 /// assert_eq!(ts.subsec_nanosecond(), 123_456_789);
1101 /// let ts = Timestamp::new(5, 999_999_999)?;
1102 /// assert_eq!(ts.subsec_nanosecond(), 999_999_999);
1103 ///
1104 /// let ts = Timestamp::new(-5, -123_456_789)?;
1105 /// assert_eq!(ts.subsec_nanosecond(), -123_456_789);
1106 /// let ts = Timestamp::new(-5, -999_999_999)?;
1107 /// assert_eq!(ts.subsec_nanosecond(), -999_999_999);
1108 ///
1109 /// # Ok::<(), Box<dyn std::error::Error>>(())
1110 /// ```
1111 #[inline]
1112 pub fn subsec_nanosecond(self) -> i32 {
1113 self.dur.subsec_nanosecond()
1114 }
1115
1116 /// Returns this timestamp as a [`SignedDuration`] since the Unix epoch.
1117 ///
1118 /// # Example
1119 ///
1120 /// ```
1121 /// use jiff::{SignedDuration, Timestamp};
1122 ///
1123 /// assert_eq!(
1124 /// Timestamp::UNIX_EPOCH.as_duration(),
1125 /// SignedDuration::ZERO,
1126 /// );
1127 /// assert_eq!(
1128 /// Timestamp::new(5, 123_456_789)?.as_duration(),
1129 /// SignedDuration::new(5, 123_456_789),
1130 /// );
1131 /// assert_eq!(
1132 /// Timestamp::new(-5, -123_456_789)?.as_duration(),
1133 /// SignedDuration::new(-5, -123_456_789),
1134 /// );
1135 ///
1136 /// # Ok::<(), Box<dyn std::error::Error>>(())
1137 /// ```
1138 #[inline]
1139 pub fn as_duration(self) -> SignedDuration {
1140 // OK because a `Timestamp` has a strictly smaller range than a duration,
1141 // _and_ because we know `|nanos| < 1` as well.
1142 SignedDuration::new_unchecked(
1143 self.dur.as_second(),
1144 self.dur.subsec_nanosecond(),
1145 )
1146 }
1147
1148 /// Returns the sign of this timestamp.
1149 ///
1150 /// This can return one of three possible values:
1151 ///
1152 /// * `0` when this timestamp is precisely equivalent to
1153 /// [`Timestamp::UNIX_EPOCH`].
1154 /// * `1` when this timestamp occurs after the Unix epoch.
1155 /// * `-1` when this timestamp occurs before the Unix epoch.
1156 ///
1157 /// The sign returned is guaranteed to match the sign of all "getter"
1158 /// methods on `Timestamp`. For example, [`Timestamp::as_second`] and
1159 /// [`Timestamp::subsec_nanosecond`]. This is true even if the signs
1160 /// of the `second` and `nanosecond` components were mixed when given to
1161 /// the [`Timestamp::new`] constructor.
1162 ///
1163 /// # Example
1164 ///
1165 /// ```
1166 /// use jiff::Timestamp;
1167 ///
1168 /// let ts = Timestamp::new(5, -999_999_999)?;
1169 /// assert_eq!(ts.signum(), 1);
1170 /// // The mixed signs were normalized away!
1171 /// assert_eq!(ts.as_second(), 4);
1172 /// assert_eq!(ts.subsec_nanosecond(), 1);
1173 ///
1174 /// // The same applies for negative timestamps.
1175 /// let ts = Timestamp::new(-5, 999_999_999)?;
1176 /// assert_eq!(ts.signum(), -1);
1177 /// assert_eq!(ts.as_second(), -4);
1178 /// assert_eq!(ts.subsec_nanosecond(), -1);
1179 ///
1180 /// # Ok::<(), Box<dyn std::error::Error>>(())
1181 /// ```
1182 #[inline]
1183 pub fn signum(self) -> i8 {
1184 self.dur.signum()
1185 }
1186
1187 /// Returns true if and only if this timestamp corresponds to the instant
1188 /// in time known as the Unix epoch.
1189 ///
1190 /// # Example
1191 ///
1192 /// ```
1193 /// use jiff::Timestamp;
1194 ///
1195 /// assert!(Timestamp::UNIX_EPOCH.is_zero());
1196 /// ```
1197 #[inline]
1198 pub fn is_zero(self) -> bool {
1199 self.dur.is_zero()
1200 }
1201
1202 /// Creates a [`ZonedDateTime`] value by attaching a time zone for the
1203 /// given name to this instant in time.
1204 ///
1205 /// The name given is resolved to a [`TimeZone`] by using the default
1206 /// [`TimeZoneDatabase`](crate::tz::TimeZoneDatabase) created by
1207 /// [`tz::db`](crate::tz::db). Indeed, this is a convenience function for
1208 /// [`Timestamp::to_zoned_datetime`] where the time zone database lookup
1209 /// is done automatically.
1210 ///
1211 /// Assuming the time zone name could be resolved to a [`TimeZone`], this
1212 /// routine is otherwise infallible and never results in any ambiguity
1213 /// since both a [`Timestamp`] and a [`ZonedDateTime`] correspond to
1214 /// precise instant in time. This is unlike
1215 /// [`civil::DateTime::to_zoned_datetime`](crate::civil::DateTime::to_zoned_datetime),
1216 /// where a civil datetime might correspond to more than one instant in
1217 /// time (i.e., a fold, typically DST ending) or no instants in time (i.e.,
1218 /// a gap, typically DST starting).
1219 ///
1220 /// # Errors
1221 ///
1222 /// This returns an error when the given time zone name could not be found
1223 /// in the default time zone database.
1224 ///
1225 /// # Example
1226 ///
1227 /// This is a simple example of converting the instant that is `123,456,789`
1228 /// seconds after the Unix epoch to an instant that is aware of its time
1229 /// zone:
1230 ///
1231 /// ```
1232 /// use jiff::Timestamp;
1233 ///
1234 /// let ts = Timestamp::new(123_456_789, 0).unwrap();
1235 /// let zdt = ts.in_tz("America/New_York")?;
1236 /// assert_eq!(zdt.to_string(), "1973-11-29T16:33:09-05:00[America/New_York]");
1237 ///
1238 /// # Ok::<(), Box<dyn std::error::Error>>(())
1239 /// ```
1240 ///
1241 /// This can be used to answer questions like, "What time was it at the
1242 /// Unix epoch in Hobart?"
1243 ///
1244 /// ```
1245 /// use jiff::Timestamp;
1246 ///
1247 /// // Time zone database lookups are case insensitive!
1248 /// let zdt = Timestamp::UNIX_EPOCH.in_tz("australia/hobart")?;
1249 /// assert_eq!(zdt.to_string(), "1970-01-01T11:00:00+11:00[Australia/Hobart]");
1250 ///
1251 /// # Ok::<(), Box<dyn std::error::Error>>(())
1252 /// ```
1253 ///
1254 /// # Example: errors
1255 ///
1256 /// This routine can return an error when the time zone is unrecognized:
1257 ///
1258 /// ```
1259 /// use jiff::Timestamp;
1260 ///
1261 /// assert!(Timestamp::UNIX_EPOCH.in_tz("does not exist").is_err());
1262 /// ```
1263 #[inline]
1264 pub fn in_tz(self, time_zone_name: &str) -> Result<ZonedDateTime, Error> {
1265 let tz = crate::tz::db().get(time_zone_name)?;
1266 Ok(self.to_zoned_datetime(tz))
1267 }
1268
1269 /// Creates a [`ZonedDateTime`] value by attaching the given time zone to
1270 /// this instant in time.
1271 ///
1272 /// This is infallible and never results in any ambiguity since both a
1273 /// [`Timestamp`] and a [`ZonedDateTime`] correspond to precise instant in
1274 /// time. This is unlike
1275 /// [`civil::DateTime::to_zoned_datetime`](crate::civil::DateTime::to_zoned_datetime),
1276 /// where a civil datetime might correspond to more than one instant in
1277 /// time (i.e., a fold, typically DST ending) or no instants in time (i.e.,
1278 /// a gap, typically DST starting).
1279 ///
1280 /// In the common case of a time zone being represented as a name string,
1281 /// like `Australia/Hobart`, consider using [`Timestamp::in_tz`]
1282 /// instead.
1283 ///
1284 /// # Example
1285 ///
1286 /// This example shows how to create a zoned value with a fixed time zone
1287 /// offset:
1288 ///
1289 /// ```
1290 /// use jiff::{tz::{self, TimeZone}, Timestamp};
1291 ///
1292 /// let ts = Timestamp::new(123_456_789, 0).unwrap();
1293 /// let tz = TimeZone::fixed(tz::offset(-4));
1294 /// let zdt = ts.to_zoned_datetime(tz);
1295 /// // A time zone annotation is still included in the printable version
1296 /// // of the ZonedDateTime value, but it is fixed to a particular offset.
1297 /// assert_eq!(zdt.to_string(), "1973-11-29T17:33:09-04:00[-04:00]");
1298 /// ```
1299 ///
1300 /// # Example: POSIX time zone strings
1301 ///
1302 /// This example shows how to create a time zone from a POSIX time zone
1303 /// string that describes the transition to and from daylight saving
1304 /// time for `America/St_Johns`. In particular, this rule uses non-zero
1305 /// minutes, which is atypical.
1306 ///
1307 /// ```
1308 /// use jiff::{tz::TimeZone, Timestamp};
1309 ///
1310 /// let ts = Timestamp::new(123_456_789, 0)?;
1311 /// let tz = TimeZone::posix("NST3:30NDT,M3.2.0,M11.1.0")?;
1312 /// let zdt = ts.to_zoned_datetime(tz);
1313 /// // There isn't any agreed upon mechanism for transmitting a POSIX time
1314 /// // zone string within an RFC 9557 TZ annotation, so Jiff just emits the
1315 /// // offset. In practice, POSIX TZ strings are rarely user facing anyway.
1316 /// // (They are still in widespread use as an implementation detail of the
1317 /// // IANA Time Zone Database however.)
1318 /// assert_eq!(zdt.to_string(), "1973-11-29T18:03:09-03:30[-03:30]");
1319 ///
1320 /// # Ok::<(), Box<dyn std::error::Error>>(())
1321 /// ```
1322 #[inline]
1323 pub fn to_zoned_datetime(self, tz: TimeZone) -> ZonedDateTime {
1324 ZonedDateTime::new(self, tz)
1325 }
1326
1327 /// Add the given span of time to this timestamp.
1328 ///
1329 /// This operation accepts three different duration types: [`Span`],
1330 /// [`SignedDuration`] or [`std::time::Duration`]. This is achieved via
1331 /// `From` trait implementations for the [`TimestampArithmetic`] type.
1332 ///
1333 /// # Properties
1334 ///
1335 /// Given a timestamp `ts1` and a span `s`, and assuming `ts2 = ts1 + s`
1336 /// exists, it follows then that `ts1 = ts2 - s` for all values of `ts1`
1337 /// and `s` that sum to a valid `ts2`.
1338 ///
1339 /// In short, subtracting the given span from the sum returned by this
1340 /// function is guaranteed to result in precisely the original timestamp.
1341 ///
1342 /// # Errors
1343 ///
1344 /// If the sum would overflow the minimum or maximum timestamp values, then
1345 /// an error is returned.
1346 ///
1347 /// This also returns an error if the given duration is a `Span` with any
1348 /// non-zero units greater than hours. If you want to use bigger units,
1349 /// convert this timestamp to a `ZonedDateTime` and use
1350 /// [`ZonedDateTime::checked_add`]. This error occurs because a `Timestamp`
1351 /// has no time zone attached to it, and thus cannot unambiguously resolve
1352 /// the length of a single day.
1353 ///
1354 /// # Example
1355 ///
1356 /// This shows how to add `5` hours to the Unix epoch:
1357 ///
1358 /// ```
1359 /// use jiff::{Timestamp, ToSpan};
1360 ///
1361 /// let ts = Timestamp::UNIX_EPOCH.checked_add(5.hours())?;
1362 /// assert_eq!(ts.to_string(), "1970-01-01T05:00:00Z");
1363 ///
1364 /// # Ok::<(), Box<dyn std::error::Error>>(())
1365 /// ```
1366 ///
1367 /// # Example: negative spans are supported
1368 ///
1369 /// This shows how to add `-5` hours to the Unix epoch. This is the same
1370 /// as subtracting `5` hours from the Unix epoch.
1371 ///
1372 /// ```
1373 /// use jiff::{Timestamp, ToSpan};
1374 ///
1375 /// let ts = Timestamp::UNIX_EPOCH.checked_add(-5.hours())?;
1376 /// assert_eq!(ts.to_string(), "1969-12-31T19:00:00Z");
1377 ///
1378 /// # Ok::<(), Box<dyn std::error::Error>>(())
1379 /// ```
1380 ///
1381 /// # Example: available via addition operator
1382 ///
1383 /// This routine can be used via the `+` operator. Note though that if it
1384 /// fails, it will result in a panic.
1385 ///
1386 /// ```
1387 /// use jiff::{Timestamp, ToSpan};
1388 ///
1389 /// let ts1 = Timestamp::new(2_999_999_999, 0)?;
1390 /// assert_eq!(ts1.to_string(), "2065-01-24T05:19:59Z");
1391 ///
1392 /// let ts2 = ts1 + 1.hour().minutes(30).nanoseconds(123);
1393 /// assert_eq!(ts2.to_string(), "2065-01-24T06:49:59.000000123Z");
1394 ///
1395 /// # Ok::<(), Box<dyn std::error::Error>>(())
1396 /// ```
1397 ///
1398 /// # Example: error on overflow
1399 ///
1400 /// ```
1401 /// use jiff::{Timestamp, ToSpan};
1402 ///
1403 /// let ts = Timestamp::MAX;
1404 /// assert_eq!(ts.to_string(), "9999-12-30T22:00:00.999999999Z");
1405 /// assert!(ts.checked_add(1.second()).is_err());
1406 /// assert!(ts.checked_add(1.nanosecond()).is_err());
1407 /// assert!(ts.checked_add(
1408 /// 175_307_616.hours().minutes(10_518_456_960i64).seconds(631_107_417_600i64),
1409 /// ).is_err());
1410 ///
1411 /// let ts = Timestamp::MIN;
1412 /// assert_eq!(ts.to_string(), "-009999-01-02T01:59:59Z");
1413 /// assert!(ts.checked_add(-1.second()).is_err());
1414 /// assert!(ts.checked_add(-1.nanosecond()).is_err());
1415 /// ```
1416 ///
1417 /// # Example: adding absolute durations
1418 ///
1419 /// This shows how to add signed and unsigned absolute durations to a
1420 /// `Timestamp`.
1421 ///
1422 /// ```
1423 /// use std::time::Duration;
1424 ///
1425 /// use jiff::{SignedDuration, Timestamp};
1426 ///
1427 /// let ts1 = Timestamp::new(2_999_999_999, 0)?;
1428 /// assert_eq!(ts1.to_string(), "2065-01-24T05:19:59Z");
1429 ///
1430 /// let dur = SignedDuration::new(60 * 60 + 30 * 60, 123);
1431 /// assert_eq!(
1432 /// ts1.checked_add(dur)?.to_string(),
1433 /// "2065-01-24T06:49:59.000000123Z",
1434 /// );
1435 ///
1436 /// let dur = Duration::new(60 * 60 + 30 * 60, 123);
1437 /// assert_eq!(
1438 /// ts1.checked_add(dur)?.to_string(),
1439 /// "2065-01-24T06:49:59.000000123Z",
1440 /// );
1441 ///
1442 /// # Ok::<(), Box<dyn std::error::Error>>(())
1443 /// ```
1444 #[inline]
1445 pub fn checked_add<A: Into<TimestampArithmetic>>(
1446 self,
1447 duration: A,
1448 ) -> Result<Timestamp, Error> {
1449 let duration: TimestampArithmetic = duration.into();
1450 duration.checked_add(self)
1451 }
1452
1453 #[inline]
1454 fn checked_add_span(self, span: &Span) -> Result<Timestamp, Error> {
1455 if let Some(err) = span.smallest_non_time_non_zero_unit_error() {
1456 return Err(err);
1457 }
1458 if span.is_zero() {
1459 return Ok(self);
1460 }
1461 // The common case is probably a span without fractional seconds, so
1462 // we specialize for that since it requires a fair bit less math.
1463 //
1464 // Note that this only works when *both* the span and timestamp lack
1465 // fractional seconds.
1466 if self.subsec_nanosecond() == 0 && !span.has_fractional_seconds() {
1467 let dur = self
1468 .dur
1469 .checked_add_seconds(span.to_hms_seconds())
1470 .map_err(Error::jcore_range)
1471 .context(E::OverflowAddSpan)?;
1472 return Ok(Timestamp { dur });
1473 }
1474 let sum = self
1475 .as_duration()
1476 .checked_add(span.to_invariant_duration())
1477 .ok_or(E::OverflowAddSpan)?;
1478 Timestamp::from_duration(sum)
1479 }
1480
1481 #[inline]
1482 fn checked_add_duration(
1483 self,
1484 duration: SignedDuration,
1485 ) -> Result<Timestamp, Error> {
1486 let start = self.as_duration();
1487 let end = start.checked_add(duration).ok_or(E::OverflowAddDuration)?;
1488 Timestamp::from_duration(end)
1489 }
1490
1491 /// This routine is identical to [`Timestamp::checked_add`] with the
1492 /// duration negated.
1493 ///
1494 /// # Errors
1495 ///
1496 /// This has the same error conditions as [`Timestamp::checked_add`].
1497 ///
1498 /// # Example
1499 ///
1500 /// This routine can be used via the `-` operator. Note though that if it
1501 /// fails, it will result in a panic.
1502 ///
1503 /// ```
1504 /// use jiff::{SignedDuration, Timestamp, ToSpan};
1505 ///
1506 /// let ts1 = Timestamp::new(2_999_999_999, 0)?;
1507 /// assert_eq!(ts1.to_string(), "2065-01-24T05:19:59Z");
1508 ///
1509 /// let ts2 = ts1 - 1.hour().minutes(30).nanoseconds(123);
1510 /// assert_eq!(ts2.to_string(), "2065-01-24T03:49:58.999999877Z");
1511 ///
1512 /// # Ok::<(), Box<dyn std::error::Error>>(())
1513 /// ```
1514 ///
1515 /// # Example: use with [`SignedDuration`] and [`std::time::Duration`]
1516 ///
1517 /// ```
1518 /// use std::time::Duration;
1519 ///
1520 /// use jiff::{SignedDuration, Timestamp};
1521 ///
1522 /// let ts1 = Timestamp::new(2_999_999_999, 0)?;
1523 /// assert_eq!(ts1.to_string(), "2065-01-24T05:19:59Z");
1524 ///
1525 /// let dur = SignedDuration::new(60 * 60 + 30 * 60, 123);
1526 /// assert_eq!(
1527 /// ts1.checked_sub(dur)?.to_string(),
1528 /// "2065-01-24T03:49:58.999999877Z",
1529 /// );
1530 ///
1531 /// let dur = Duration::new(60 * 60 + 30 * 60, 123);
1532 /// assert_eq!(
1533 /// ts1.checked_sub(dur)?.to_string(),
1534 /// "2065-01-24T03:49:58.999999877Z",
1535 /// );
1536 ///
1537 /// # Ok::<(), Box<dyn std::error::Error>>(())
1538 /// ```
1539 #[inline]
1540 pub fn checked_sub<A: Into<TimestampArithmetic>>(
1541 self,
1542 duration: A,
1543 ) -> Result<Timestamp, Error> {
1544 let duration: TimestampArithmetic = duration.into();
1545 duration.checked_neg().and_then(|ta| ta.checked_add(self))
1546 }
1547
1548 /// This routine is identical to [`Timestamp::checked_add`], except the
1549 /// result saturates on overflow. That is, instead of overflow, either
1550 /// [`Timestamp::MIN`] or [`Timestamp::MAX`] is returned.
1551 ///
1552 /// # Errors
1553 ///
1554 /// This returns an error if the given `Span` contains any non-zero units
1555 /// greater than hours.
1556 ///
1557 /// # Example
1558 ///
1559 /// This example shows that arithmetic saturates on overflow.
1560 ///
1561 /// ```
1562 /// use jiff::{SignedDuration, Timestamp, ToSpan};
1563 ///
1564 /// assert_eq!(
1565 /// Timestamp::MAX,
1566 /// Timestamp::MAX.saturating_add(1.nanosecond())?,
1567 /// );
1568 /// assert_eq!(
1569 /// Timestamp::MIN,
1570 /// Timestamp::MIN.saturating_add(-1.nanosecond())?,
1571 /// );
1572 /// assert_eq!(
1573 /// Timestamp::MAX,
1574 /// Timestamp::UNIX_EPOCH.saturating_add(SignedDuration::MAX)?,
1575 /// );
1576 /// assert_eq!(
1577 /// Timestamp::MIN,
1578 /// Timestamp::UNIX_EPOCH.saturating_add(SignedDuration::MIN)?,
1579 /// );
1580 /// assert_eq!(
1581 /// Timestamp::MAX,
1582 /// Timestamp::UNIX_EPOCH.saturating_add(std::time::Duration::MAX)?,
1583 /// );
1584 ///
1585 /// # Ok::<(), Box<dyn std::error::Error>>(())
1586 /// ```
1587 #[inline]
1588 pub fn saturating_add<A: Into<TimestampArithmetic>>(
1589 self,
1590 duration: A,
1591 ) -> Result<Timestamp, Error> {
1592 let duration: TimestampArithmetic = duration.into();
1593 duration.saturating_add(self)
1594 }
1595
1596 /// This routine is identical to [`Timestamp::saturating_add`] with the
1597 /// span parameter negated.
1598 ///
1599 /// # Errors
1600 ///
1601 /// This returns an error if the given `Span` contains any non-zero units
1602 /// greater than hours.
1603 ///
1604 /// # Example
1605 ///
1606 /// This example shows that arithmetic saturates on overflow.
1607 ///
1608 /// ```
1609 /// use jiff::{SignedDuration, Timestamp, ToSpan};
1610 ///
1611 /// assert_eq!(
1612 /// Timestamp::MIN,
1613 /// Timestamp::MIN.saturating_sub(1.nanosecond())?,
1614 /// );
1615 /// assert_eq!(
1616 /// Timestamp::MAX,
1617 /// Timestamp::MAX.saturating_sub(-1.nanosecond())?,
1618 /// );
1619 /// assert_eq!(
1620 /// Timestamp::MIN,
1621 /// Timestamp::UNIX_EPOCH.saturating_sub(SignedDuration::MAX)?,
1622 /// );
1623 /// assert_eq!(
1624 /// Timestamp::MAX,
1625 /// Timestamp::UNIX_EPOCH.saturating_sub(SignedDuration::MIN)?,
1626 /// );
1627 /// assert_eq!(
1628 /// Timestamp::MIN,
1629 /// Timestamp::UNIX_EPOCH.saturating_sub(std::time::Duration::MAX)?,
1630 /// );
1631 ///
1632 /// # Ok::<(), Box<dyn std::error::Error>>(())
1633 /// ```
1634 #[inline]
1635 pub fn saturating_sub<A: Into<TimestampArithmetic>>(
1636 self,
1637 duration: A,
1638 ) -> Result<Timestamp, Error> {
1639 let duration: TimestampArithmetic = duration.into();
1640 let Ok(duration) = duration.checked_neg() else {
1641 return Ok(Timestamp::MIN);
1642 };
1643 self.saturating_add(duration)
1644 }
1645
1646 /// Returns a span representing the elapsed time from this timestamp until
1647 /// the given `other` timestamp.
1648 ///
1649 /// When `other` occurs before this timestamp, then the span returned will
1650 /// be negative.
1651 ///
1652 /// Depending on the input provided, the span returned is rounded. It may
1653 /// also be balanced up to bigger units than the default. By default,
1654 /// the span returned is balanced such that the biggest possible unit is
1655 /// seconds.
1656 ///
1657 /// This operation is configured by providing a [`TimestampDifference`]
1658 /// value. Since this routine accepts anything that implements
1659 /// `Into<TimestampDifference>`, once can pass a `Timestamp` directly.
1660 /// One can also pass a `(Unit, Timestamp)`, where `Unit` is treated as
1661 /// [`TimestampDifference::largest`].
1662 ///
1663 /// # Properties
1664 ///
1665 /// It is guaranteed that if the returned span is subtracted from `other`,
1666 /// and if no rounding is requested, then the original timestamp will be
1667 /// returned.
1668 ///
1669 /// This routine is equivalent to `self.since(other).map(|span| -span)`
1670 /// if no rounding options are set. If rounding options are set, then
1671 /// it's equivalent to
1672 /// `self.since(other_without_rounding_options).map(|span| -span)`,
1673 /// followed by a call to [`Span::round`] with the appropriate rounding
1674 /// options set. This is because the negation of a span can result in
1675 /// different rounding results depending on the rounding mode.
1676 ///
1677 /// # Errors
1678 ///
1679 /// An error can occur in some cases when the requested configuration
1680 /// would result in a span that is beyond allowable limits. For example,
1681 /// the nanosecond component of a span cannot represent the span of
1682 /// time between the minimum and maximum timestamps supported by Jiff.
1683 /// Therefore, if one requests a span with its largest unit set to
1684 /// [`Unit::Nanosecond`], then it's possible for this routine to fail.
1685 ///
1686 /// An error can also occur if `TimestampDifference` is misconfigured. For
1687 /// example, if the smallest unit provided is bigger than the largest unit,
1688 /// or if the largest unit provided is bigger than hours. (To use bigger
1689 /// units with an instant in time, use [`ZonedDateTime::until`] instead.)
1690 ///
1691 /// It is guaranteed that if one provides a timestamp with the default
1692 /// [`TimestampDifference`] configuration, then this routine will never
1693 /// fail.
1694 ///
1695 /// # Example
1696 ///
1697 /// ```
1698 /// use jiff::{Timestamp, ToSpan};
1699 ///
1700 /// let earlier: Timestamp = "2006-08-24T22:30:00Z".parse()?;
1701 /// let later: Timestamp = "2019-01-31 21:00:00Z".parse()?;
1702 /// assert_eq!(earlier.until(later)?, 392509800.seconds().fieldwise());
1703 ///
1704 /// // Flipping the timestamps is fine, but you'll get a negative span.
1705 /// assert_eq!(later.until(earlier)?, -392509800.seconds().fieldwise());
1706 ///
1707 /// # Ok::<(), Box<dyn std::error::Error>>(())
1708 /// ```
1709 ///
1710 /// # Example: using bigger units
1711 ///
1712 /// This example shows how to expand the span returned to bigger units.
1713 /// This makes use of a `From<(Unit, Timestamp)> for TimestampDifference`
1714 /// trait implementation.
1715 ///
1716 /// ```
1717 /// use jiff::{Timestamp, ToSpan, Unit};
1718 ///
1719 /// let ts1: Timestamp = "1995-12-07T03:24:30.000003500Z".parse()?;
1720 /// let ts2: Timestamp = "2019-01-31 15:30:00Z".parse()?;
1721 ///
1722 /// // The default limits durations to using "seconds" as the biggest unit.
1723 /// let span = ts1.until(ts2)?;
1724 /// assert_eq!(span.to_string(), "PT730641929.9999965S");
1725 ///
1726 /// // But we can ask for units all the way up to hours.
1727 /// let span = ts1.until((Unit::Hour, ts2))?;
1728 /// assert_eq!(span.to_string(), "PT202956H5M29.9999965S");
1729 ///
1730 /// # Ok::<(), Box<dyn std::error::Error>>(())
1731 /// ```
1732 ///
1733 /// # Example: rounding the result
1734 ///
1735 /// This shows how one might find the difference between two timestamps and
1736 /// have the result rounded such that sub-seconds are removed.
1737 ///
1738 /// In this case, we need to hand-construct a [`TimestampDifference`]
1739 /// in order to gain full configurability.
1740 ///
1741 /// ```
1742 /// use jiff::{Timestamp, TimestampDifference, ToSpan, Unit};
1743 ///
1744 /// let ts1: Timestamp = "1995-12-07 03:24:30.000003500Z".parse()?;
1745 /// let ts2: Timestamp = "2019-01-31 15:30:00Z".parse()?;
1746 ///
1747 /// let span = ts1.until(
1748 /// TimestampDifference::from(ts2).smallest(Unit::Second),
1749 /// )?;
1750 /// assert_eq!(span.to_string(), "PT730641929S");
1751 ///
1752 /// // We can combine smallest and largest units too!
1753 /// let span = ts1.until(
1754 /// TimestampDifference::from(ts2)
1755 /// .smallest(Unit::Second)
1756 /// .largest(Unit::Hour),
1757 /// )?;
1758 /// assert_eq!(span.to_string(), "PT202956H5M29S");
1759 /// # Ok::<(), Box<dyn std::error::Error>>(())
1760 /// ```
1761 #[inline]
1762 pub fn until<A: Into<TimestampDifference>>(
1763 self,
1764 other: A,
1765 ) -> Result<Span, Error> {
1766 let args: TimestampDifference = other.into();
1767 let span = args.until_with_largest_unit(self)?;
1768 if args.rounding_may_change_span() {
1769 span.round(args.round)
1770 } else {
1771 Ok(span)
1772 }
1773 }
1774
1775 /// This routine is identical to [`Timestamp::until`], but the order of the
1776 /// parameters is flipped.
1777 ///
1778 /// # Errors
1779 ///
1780 /// This has the same error conditions as [`Timestamp::until`].
1781 ///
1782 /// # Example
1783 ///
1784 /// This routine can be used via the `-` operator. Since the default
1785 /// configuration is used and because a `Span` can represent the difference
1786 /// between any two possible timestamps, it will never panic.
1787 ///
1788 /// ```
1789 /// use jiff::{SignedDuration, Timestamp};
1790 ///
1791 /// let earlier: Timestamp = "2006-08-24T22:30:00Z".parse()?;
1792 /// let later: Timestamp = "2019-01-31 21:00:00Z".parse()?;
1793 /// assert_eq!(later - earlier, SignedDuration::from_secs(392_509_800));
1794 ///
1795 /// # Ok::<(), Box<dyn std::error::Error>>(())
1796 /// ```
1797 #[inline]
1798 pub fn since<A: Into<TimestampDifference>>(
1799 self,
1800 other: A,
1801 ) -> Result<Span, Error> {
1802 let args: TimestampDifference = other.into();
1803 let span = -args.until_with_largest_unit(self)?;
1804 if args.rounding_may_change_span() {
1805 span.round(args.round)
1806 } else {
1807 Ok(span)
1808 }
1809 }
1810
1811 /// Returns an absolute duration representing the elapsed time from this
1812 /// timestamp until the given `other` timestamp.
1813 ///
1814 /// When `other` occurs before this timestamp, then the duration returned
1815 /// will be negative.
1816 ///
1817 /// Unlike [`Timestamp::until`], this always returns a duration
1818 /// corresponding to a 96-bit integer of nanoseconds between two
1819 /// timestamps.
1820 ///
1821 /// # Fallibility
1822 ///
1823 /// This routine never panics or returns an error. Since there are no
1824 /// configuration options that can be incorrectly provided, no error is
1825 /// possible when calling this routine. In contrast, [`Timestamp::until`]
1826 /// can return an error in some cases due to misconfiguration. But like
1827 /// this routine, [`Timestamp::until`] never panics or returns an error in
1828 /// its default configuration.
1829 ///
1830 /// # When should I use this versus [`Timestamp::until`]?
1831 ///
1832 /// See the type documentation for [`SignedDuration`] for the section on
1833 /// when one should use [`Span`] and when one should use `SignedDuration`.
1834 /// In short, use `Span` (and therefore `Timestamp::until`) unless you have
1835 /// a specific reason to do otherwise.
1836 ///
1837 /// # Example
1838 ///
1839 /// ```
1840 /// use jiff::{Timestamp, SignedDuration};
1841 ///
1842 /// let earlier: Timestamp = "2006-08-24T22:30:00Z".parse()?;
1843 /// let later: Timestamp = "2019-01-31 21:00:00Z".parse()?;
1844 /// assert_eq!(
1845 /// earlier.duration_until(later),
1846 /// SignedDuration::from_secs(392509800),
1847 /// );
1848 ///
1849 /// // Flipping the timestamps is fine, but you'll get a negative span.
1850 /// assert_eq!(
1851 /// later.duration_until(earlier),
1852 /// SignedDuration::from_secs(-392509800),
1853 /// );
1854 ///
1855 /// # Ok::<(), Box<dyn std::error::Error>>(())
1856 /// ```
1857 ///
1858 /// # Example: difference with [`Timestamp::until`]
1859 ///
1860 /// The primary difference between this routine and
1861 /// `Timestamp::until`, other than the return type, is that this
1862 /// routine is likely to be faster. Namely, it does simple 96-bit
1863 /// integer math, where as `Timestamp::until` has to do a bit more
1864 /// work to deal with the different types of units on a `Span`.
1865 ///
1866 /// Additionally, since the difference between two timestamps is always
1867 /// expressed in units of hours or smaller, and units of hours or smaller
1868 /// are always uniform, there is no "expressive" difference between this
1869 /// routine and `Timestamp::until`. Because of this, one can always
1870 /// convert between `Span` and `SignedDuration` as returned by methods
1871 /// on `Timestamp` without a relative datetime:
1872 ///
1873 /// ```
1874 /// use jiff::{SignedDuration, Span, Timestamp};
1875 ///
1876 /// let ts1: Timestamp = "2024-02-28T00:00:00Z".parse()?;
1877 /// let ts2: Timestamp = "2024-03-01T00:00:00Z".parse()?;
1878 /// let dur = ts1.duration_until(ts2);
1879 /// // Guaranteed to never fail because the duration
1880 /// // between two civil times never exceeds the limits
1881 /// // of a `Span`.
1882 /// let span = Span::try_from(dur).unwrap();
1883 /// assert_eq!(format!("{span:#}"), "172800s");
1884 /// // Guaranteed to succeed and always return the original
1885 /// // duration because the units are always hours or smaller,
1886 /// // and thus uniform. This means a relative datetime is
1887 /// // never required to do this conversion.
1888 /// let dur = SignedDuration::try_from(span).unwrap();
1889 /// assert_eq!(dur, SignedDuration::from_secs(172_800));
1890 ///
1891 /// # Ok::<(), Box<dyn std::error::Error>>(())
1892 /// ```
1893 ///
1894 /// This conversion guarantee also applies to [`Timestamp::until`] since it
1895 /// always returns a balanced span. That is, it never returns spans like
1896 /// `1 second 1000 milliseconds`. (Those cannot be losslessly converted to
1897 /// a `SignedDuration` since a `SignedDuration` is only represented as a
1898 /// single 96-bit integer of nanoseconds.)
1899 #[inline]
1900 pub fn duration_until(self, other: Timestamp) -> SignedDuration {
1901 SignedDuration::timestamp_until(self, other)
1902 }
1903
1904 /// This routine is identical to [`Timestamp::duration_until`], but the
1905 /// order of the parameters is flipped.
1906 ///
1907 /// # Example
1908 ///
1909 /// ```
1910 /// use jiff::{SignedDuration, Timestamp};
1911 ///
1912 /// let earlier: Timestamp = "2006-08-24T22:30:00Z".parse()?;
1913 /// let later: Timestamp = "2019-01-31 21:00:00Z".parse()?;
1914 /// assert_eq!(
1915 /// later.duration_since(earlier),
1916 /// SignedDuration::from_secs(392509800),
1917 /// );
1918 ///
1919 /// # Ok::<(), Box<dyn std::error::Error>>(())
1920 /// ```
1921 #[inline]
1922 pub fn duration_since(self, other: Timestamp) -> SignedDuration {
1923 SignedDuration::timestamp_until(other, self)
1924 }
1925
1926 /// Rounds this timestamp according to the [`TimestampRound`] configuration
1927 /// given.
1928 ///
1929 /// The principal option is [`TimestampRound::smallest`], which allows
1930 /// one to configure the smallest units in the returned timestamp.
1931 /// Rounding is what determines whether the specified smallest unit
1932 /// should keep its current value or whether it should be incremented.
1933 /// Moreover, the amount it should be incremented can be configured via
1934 /// [`TimestampRound::increment`]. Finally, the rounding strategy itself
1935 /// can be configured via [`TimestampRound::mode`].
1936 ///
1937 /// Note that this routine is generic and accepts anything that
1938 /// implements `Into<TimestampRound>`. Some notable implementations are:
1939 ///
1940 /// * `From<Unit> for TimestampRound`, which will automatically create a
1941 /// `TimestampRound::new().smallest(unit)` from the unit provided.
1942 /// * `From<(Unit, i64)> for TimestampRound`, which will automatically
1943 /// create a `TimestampRound::new().smallest(unit).increment(number)` from
1944 /// the unit and increment provided.
1945 ///
1946 /// # Errors
1947 ///
1948 /// This returns an error if the smallest unit configured on the given
1949 /// [`TimestampRound`] is bigger than hours.
1950 ///
1951 /// The rounding increment, when combined with the smallest unit (which
1952 /// defaults to [`Unit::Nanosecond`]), must divide evenly into `86,400`
1953 /// seconds (one 24-hour civil day). For example, increments of both
1954 /// 45 seconds and 15 minutes are allowed, but 7 seconds and 25 minutes are
1955 /// both not allowed.
1956 ///
1957 /// # Example
1958 ///
1959 /// This is a basic example that demonstrates rounding a timestamp to the
1960 /// nearest hour. This also demonstrates calling this method with the
1961 /// smallest unit directly, instead of constructing a `TimestampRound`
1962 /// manually.
1963 ///
1964 /// ```
1965 /// use jiff::{Timestamp, Unit};
1966 ///
1967 /// let ts: Timestamp = "2024-06-19 15:30:00Z".parse()?;
1968 /// assert_eq!(
1969 /// ts.round(Unit::Hour)?.to_string(),
1970 /// "2024-06-19T16:00:00Z",
1971 /// );
1972 /// let ts: Timestamp = "2024-06-19 15:29:59Z".parse()?;
1973 /// assert_eq!(
1974 /// ts.round(Unit::Hour)?.to_string(),
1975 /// "2024-06-19T15:00:00Z",
1976 /// );
1977 ///
1978 /// # Ok::<(), Box<dyn std::error::Error>>(())
1979 /// ```
1980 ///
1981 /// # Example: changing the rounding mode
1982 ///
1983 /// The default rounding mode is [`RoundMode::HalfExpand`], which
1984 /// breaks ties by rounding away from zero. But other modes like
1985 /// [`RoundMode::Trunc`] can be used too:
1986 ///
1987 /// ```
1988 /// use jiff::{RoundMode, Timestamp, TimestampRound, Unit};
1989 ///
1990 /// // The default will round up to the next hour for any time past the
1991 /// // 30 minute mark, but using truncation rounding will always round
1992 /// // down.
1993 /// let ts: Timestamp = "2024-06-19 15:30:00Z".parse()?;
1994 /// assert_eq!(
1995 /// ts.round(
1996 /// TimestampRound::new()
1997 /// .smallest(Unit::Hour)
1998 /// .mode(RoundMode::Trunc),
1999 /// )?.to_string(),
2000 /// "2024-06-19T15:00:00Z",
2001 /// );
2002 ///
2003 /// # Ok::<(), Box<dyn std::error::Error>>(())
2004 /// ```
2005 ///
2006 /// # Example: rounding to the nearest 5 minute increment
2007 ///
2008 /// ```
2009 /// use jiff::{Timestamp, Unit};
2010 ///
2011 /// // rounds down
2012 /// let ts: Timestamp = "2024-06-19T15:27:29.999999999Z".parse()?;
2013 /// assert_eq!(
2014 /// ts.round((Unit::Minute, 5))?.to_string(),
2015 /// "2024-06-19T15:25:00Z",
2016 /// );
2017 /// // rounds up
2018 /// let ts: Timestamp = "2024-06-19T15:27:30Z".parse()?;
2019 /// assert_eq!(
2020 /// ts.round((Unit::Minute, 5))?.to_string(),
2021 /// "2024-06-19T15:30:00Z",
2022 /// );
2023 ///
2024 /// # Ok::<(), Box<dyn std::error::Error>>(())
2025 /// ```
2026 #[inline]
2027 pub fn round<R: Into<TimestampRound>>(
2028 self,
2029 options: R,
2030 ) -> Result<Timestamp, Error> {
2031 let options: TimestampRound = options.into();
2032 options.round(self)
2033 }
2034
2035 /// Return an iterator of periodic timestamps determined by the given span.
2036 ///
2037 /// The given span may be negative, in which case, the iterator will move
2038 /// backwards through time. The iterator won't stop until either the span
2039 /// itself overflows, or it would otherwise exceed the minimum or maximum
2040 /// `Timestamp` value.
2041 ///
2042 /// # Example: when to check a glucose monitor
2043 ///
2044 /// When my cat had diabetes, my veterinarian installed a glucose monitor
2045 /// and instructed me to scan it about every 5 hours. This example lists
2046 /// all of the times I need to scan it for the 2 days following its
2047 /// installation:
2048 ///
2049 /// ```
2050 /// use jiff::{Timestamp, ToSpan};
2051 ///
2052 /// let start: Timestamp = "2023-07-15 16:30:00-04".parse()?;
2053 /// let end = start.checked_add(48.hours())?;
2054 /// let mut scan_times = vec![];
2055 /// for ts in start.series(5.hours()).take_while(|&ts| ts <= end) {
2056 /// scan_times.push(ts);
2057 /// }
2058 /// assert_eq!(scan_times, vec![
2059 /// "2023-07-15 16:30:00-04:00".parse::<Timestamp>()?,
2060 /// "2023-07-15 21:30:00-04:00".parse::<Timestamp>()?,
2061 /// "2023-07-16 02:30:00-04:00".parse::<Timestamp>()?,
2062 /// "2023-07-16 07:30:00-04:00".parse::<Timestamp>()?,
2063 /// "2023-07-16 12:30:00-04:00".parse::<Timestamp>()?,
2064 /// "2023-07-16 17:30:00-04:00".parse::<Timestamp>()?,
2065 /// "2023-07-16 22:30:00-04:00".parse::<Timestamp>()?,
2066 /// "2023-07-17 03:30:00-04:00".parse::<Timestamp>()?,
2067 /// "2023-07-17 08:30:00-04:00".parse::<Timestamp>()?,
2068 /// "2023-07-17 13:30:00-04:00".parse::<Timestamp>()?,
2069 /// ]);
2070 ///
2071 /// # Ok::<(), Box<dyn std::error::Error>>(())
2072 /// ```
2073 #[inline]
2074 pub fn series(self, period: Span) -> TimestampSeries {
2075 TimestampSeries::new(self, period)
2076 }
2077}
2078
2079/// Parsing and formatting APIs.
2080impl Timestamp {
2081 /// Parses a timestamp (expressed as broken down time) in `input` matching
2082 /// the given `format`.
2083 ///
2084 /// The format string uses a "printf"-style API where conversion
2085 /// specifiers can be used as place holders to match components of
2086 /// a datetime. For details on the specifiers supported, see the
2087 /// [`fmt::strtime`] module documentation.
2088 ///
2089 /// # Errors
2090 ///
2091 /// This returns an error when parsing failed. This might happen because
2092 /// the format string itself was invalid, or because the input didn't match
2093 /// the format string.
2094 ///
2095 /// This also returns an error if there wasn't sufficient information to
2096 /// construct a timestamp. For example, if an offset wasn't parsed. (The
2097 /// offset is needed to turn the civil time parsed into a precise instant
2098 /// in time.)
2099 ///
2100 /// # Example
2101 ///
2102 /// This example shows how to parse a datetime string into a timestamp:
2103 ///
2104 /// ```
2105 /// use jiff::Timestamp;
2106 ///
2107 /// let ts = Timestamp::strptime("%F %H:%M %:z", "2024-07-14 21:14 -04:00")?;
2108 /// assert_eq!(ts.to_string(), "2024-07-15T01:14:00Z");
2109 ///
2110 /// # Ok::<(), Box<dyn std::error::Error>>(())
2111 /// ```
2112 #[inline]
2113 pub fn strptime(
2114 format: impl AsRef<[u8]>,
2115 input: impl AsRef<[u8]>,
2116 ) -> Result<Timestamp, Error> {
2117 fmt::strtime::parse(format, input).and_then(|tm| tm.to_timestamp())
2118 }
2119
2120 /// Formats this timestamp according to the given `format`.
2121 ///
2122 /// The format string uses a "printf"-style API where conversion
2123 /// specifiers can be used as place holders to format components of
2124 /// a datetime. For details on the specifiers supported, see the
2125 /// [`fmt::strtime`] module documentation.
2126 ///
2127 /// The `%Z` specifier is always formatted as `UTC`.
2128 ///
2129 /// # Errors and panics
2130 ///
2131 /// This will never error or panic. In particular,
2132 /// [lenient mode](crate::fmt::strtime::Config::lenient) is enabled, which
2133 /// means that all possible strings have some non-error interpretation.
2134 /// Note that because of this, and since Jiff may add new conversion
2135 /// specifiers in the future, the behavior of a format string may change
2136 /// when it would otherwise be invalid.
2137 ///
2138 /// To format in a way that surfaces errors, use either
2139 /// [`fmt::strtime::format`] or [`fmt::strtime::BrokenDownTime::format`].
2140 ///
2141 /// # Example
2142 ///
2143 /// This shows how to format a timestamp into a human readable datetime
2144 /// in UTC:
2145 ///
2146 /// ```
2147 /// use jiff::Timestamp;
2148 ///
2149 /// let ts = Timestamp::from_second(86_400)?;
2150 /// let string = ts.strftime("%a %b %e %I:%M:%S %p %Z %Y").to_string();
2151 /// assert_eq!(string, "Fri Jan 2 12:00:00 AM UTC 1970");
2152 ///
2153 /// # Ok::<(), Box<dyn std::error::Error>>(())
2154 /// ```
2155 ///
2156 /// # Example: errors are silently ignored
2157 ///
2158 /// If the formatting string is malformed in some way, then it is silently
2159 /// ignored. For example, when using an invalid formatting directive:
2160 ///
2161 /// ```
2162 /// use jiff::Timestamp;
2163 ///
2164 /// let ts = Timestamp::UNIX_EPOCH;
2165 /// let string = ts.strftime("%Y %").to_string();
2166 /// assert_eq!(string, "1970 %");
2167 /// ```
2168 ///
2169 /// If one wants to surface errors from a formatting string, use a lower
2170 /// level API:
2171 ///
2172 /// ```
2173 /// use jiff::Timestamp;
2174 ///
2175 /// let ts = Timestamp::UNIX_EPOCH;
2176 /// assert_eq!(
2177 /// jiff::fmt::strtime::format("%Y %", ts).unwrap_err().to_string(),
2178 /// "strftime formatting failed: invalid format string, \
2179 /// expected byte after `%`, but found end of format string",
2180 /// );
2181 /// ```
2182 #[inline]
2183 pub fn strftime<'f, F: 'f + ?Sized + AsRef<[u8]>>(
2184 &self,
2185 format: &'f F,
2186 ) -> fmt::strtime::Display<'f> {
2187 fmt::strtime::Display { fmt: format.as_ref(), tm: (*self).into() }
2188 }
2189
2190 /// Format a `Timestamp` datetime into a string with the given offset.
2191 ///
2192 /// This will format to an RFC 3339 compatible string with an offset.
2193 ///
2194 /// This will never use either `Z` (for Zulu time) or `-00:00` as an
2195 /// offset. This is because Zulu time (and `-00:00`) mean "the time in UTC
2196 /// is known, but the offset to local time is unknown." Since this routine
2197 /// accepts an explicit offset, the offset is known. For example,
2198 /// `Offset::UTC` will be formatted as `+00:00`.
2199 ///
2200 /// To format an RFC 3339 string in Zulu time, use the default
2201 /// [`std::fmt::Display`] trait implementation on `Timestamp`.
2202 ///
2203 /// # Example
2204 ///
2205 /// ```
2206 /// use jiff::{tz, Timestamp};
2207 ///
2208 /// let ts = Timestamp::from_second(1)?;
2209 /// assert_eq!(
2210 /// ts.display_with_offset(tz::offset(-5)).to_string(),
2211 /// "1969-12-31T19:00:01-05:00",
2212 /// );
2213 ///
2214 /// # Ok::<(), Box<dyn std::error::Error>>(())
2215 /// ```
2216 #[inline]
2217 pub fn display_with_offset(
2218 &self,
2219 offset: Offset,
2220 ) -> TimestampDisplayWithOffset {
2221 TimestampDisplayWithOffset { timestamp: *self, offset }
2222 }
2223}
2224
2225/// Internal APIs.
2226impl Timestamp {
2227 #[inline]
2228 pub(crate) const fn to_jcore(&self) -> JTimestamp {
2229 self.dur
2230 }
2231
2232 #[inline]
2233 pub(crate) const fn from_jcore(timestamp: JTimestamp) -> Timestamp {
2234 Timestamp { dur: timestamp }
2235 }
2236}
2237
2238impl Default for Timestamp {
2239 #[inline]
2240 fn default() -> Timestamp {
2241 Timestamp::UNIX_EPOCH
2242 }
2243}
2244
2245/// Converts a `Timestamp` datetime into a human readable datetime string.
2246///
2247/// (This `Debug` representation currently emits the same string as the
2248/// `Display` representation, but this is not a guarantee.)
2249///
2250/// Options currently supported:
2251///
2252/// * [`std::fmt::Formatter::precision`] can be set to control the precision
2253/// of the fractional second component.
2254///
2255/// # Example
2256///
2257/// ```
2258/// use jiff::Timestamp;
2259///
2260/// let ts = Timestamp::new(1_123_456_789, 123_000_000)?;
2261/// assert_eq!(
2262/// format!("{ts:.6?}"),
2263/// "2005-08-07T23:19:49.123000Z",
2264/// );
2265/// // Precision values greater than 9 are clamped to 9.
2266/// assert_eq!(
2267/// format!("{ts:.300?}"),
2268/// "2005-08-07T23:19:49.123000000Z",
2269/// );
2270/// // A precision of 0 implies the entire fractional
2271/// // component is always truncated.
2272/// assert_eq!(
2273/// format!("{ts:.0?}"),
2274/// "2005-08-07T23:19:49Z",
2275/// );
2276///
2277/// # Ok::<(), Box<dyn std::error::Error>>(())
2278/// ```
2279impl core::fmt::Debug for Timestamp {
2280 #[inline]
2281 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2282 core::fmt::Display::fmt(self, f)
2283 }
2284}
2285
2286/// Converts a `Timestamp` datetime into a RFC 3339 compliant string.
2287///
2288/// Since a `Timestamp` never has an offset associated with it and is always
2289/// in UTC, the string emitted by this trait implementation uses `Z` for "Zulu"
2290/// time. The significance of Zulu time is prescribed by RFC 9557 and means
2291/// that "the time in UTC is known, but the offset to local time is unknown."
2292/// If you need to emit an RFC 3339 compliant string with a specific offset,
2293/// then use [`Timestamp::display_with_offset`].
2294///
2295/// # Formatting options supported
2296///
2297/// * [`std::fmt::Formatter::precision`] can be set to control the precision
2298/// of the fractional second component. When not set, the minimum precision
2299/// required to losslessly render the value is used.
2300///
2301/// # Example
2302///
2303/// This shows the default rendering:
2304///
2305/// ```
2306/// use jiff::Timestamp;
2307///
2308/// // No fractional seconds.
2309/// let ts = Timestamp::from_second(1_123_456_789)?;
2310/// assert_eq!(format!("{ts}"), "2005-08-07T23:19:49Z");
2311///
2312/// // With fractional seconds.
2313/// let ts = Timestamp::new(1_123_456_789, 123_000_000)?;
2314/// assert_eq!(format!("{ts}"), "2005-08-07T23:19:49.123Z");
2315///
2316/// # Ok::<(), Box<dyn std::error::Error>>(())
2317/// ```
2318///
2319/// # Example: setting the precision
2320///
2321/// ```
2322/// use jiff::Timestamp;
2323///
2324/// let ts = Timestamp::new(1_123_456_789, 123_000_000)?;
2325/// assert_eq!(
2326/// format!("{ts:.6}"),
2327/// "2005-08-07T23:19:49.123000Z",
2328/// );
2329/// // Precision values greater than 9 are clamped to 9.
2330/// assert_eq!(
2331/// format!("{ts:.300}"),
2332/// "2005-08-07T23:19:49.123000000Z",
2333/// );
2334/// // A precision of 0 implies the entire fractional
2335/// // component is always truncated.
2336/// assert_eq!(
2337/// format!("{ts:.0}"),
2338/// "2005-08-07T23:19:49Z",
2339/// );
2340///
2341/// # Ok::<(), Box<dyn std::error::Error>>(())
2342/// ```
2343impl core::fmt::Display for Timestamp {
2344 #[inline]
2345 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2346 use crate::fmt::StdFmtWrite;
2347
2348 let precision =
2349 f.precision().map(|p| u8::try_from(p).unwrap_or(u8::MAX));
2350 temporal::DateTimePrinter::new()
2351 .precision(precision)
2352 .print_timestamp(self, StdFmtWrite(f))
2353 .map_err(|_| core::fmt::Error)
2354 }
2355}
2356
2357impl core::str::FromStr for Timestamp {
2358 type Err = Error;
2359
2360 #[inline]
2361 fn from_str(string: &str) -> Result<Timestamp, Error> {
2362 DEFAULT_DATETIME_PARSER.parse_timestamp(string)
2363 }
2364}
2365
2366impl Eq for Timestamp {}
2367
2368impl PartialEq for Timestamp {
2369 #[inline]
2370 fn eq(&self, rhs: &Timestamp) -> bool {
2371 self.dur == rhs.dur
2372 }
2373}
2374
2375impl Ord for Timestamp {
2376 #[inline]
2377 fn cmp(&self, rhs: &Timestamp) -> core::cmp::Ordering {
2378 self.dur.cmp(&rhs.dur)
2379 }
2380}
2381
2382impl PartialOrd for Timestamp {
2383 #[inline]
2384 fn partial_cmp(&self, rhs: &Timestamp) -> Option<core::cmp::Ordering> {
2385 Some(self.cmp(rhs))
2386 }
2387}
2388
2389impl core::hash::Hash for Timestamp {
2390 #[inline]
2391 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
2392 self.dur.hash(state);
2393 }
2394}
2395
2396/// Adds a span of time to a timestamp.
2397///
2398/// This uses checked arithmetic and panics when it fails. To handle arithmetic
2399/// without panics, use [`Timestamp::checked_add`]. Note that the failure
2400/// condition includes overflow and using a `Span` with non-zero units greater
2401/// than hours.
2402impl core::ops::Add<Span> for Timestamp {
2403 type Output = Timestamp;
2404
2405 #[inline]
2406 fn add(self, rhs: Span) -> Timestamp {
2407 self.checked_add_span(&rhs).expect("adding span to timestamp failed")
2408 }
2409}
2410
2411/// Adds a span of time to a timestamp in place.
2412///
2413/// This uses checked arithmetic and panics when it fails. To handle arithmetic
2414/// without panics, use [`Timestamp::checked_add`]. Note that the failure
2415/// condition includes overflow and using a `Span` with non-zero units greater
2416/// than hours.
2417impl core::ops::AddAssign<Span> for Timestamp {
2418 #[inline]
2419 fn add_assign(&mut self, rhs: Span) {
2420 *self = *self + rhs
2421 }
2422}
2423
2424/// Subtracts a span of time from a timestamp.
2425///
2426/// This uses checked arithmetic and panics when it fails. To handle arithmetic
2427/// without panics, use [`Timestamp::checked_sub`]. Note that the failure
2428/// condition includes overflow and using a `Span` with non-zero units greater
2429/// than hours.
2430impl core::ops::Sub<Span> for Timestamp {
2431 type Output = Timestamp;
2432
2433 #[inline]
2434 fn sub(self, rhs: Span) -> Timestamp {
2435 self.checked_add_span(&rhs.negate())
2436 .expect("subtracting span from timestamp failed")
2437 }
2438}
2439
2440/// Subtracts a span of time from a timestamp in place.
2441///
2442/// This uses checked arithmetic and panics when it fails. To handle arithmetic
2443/// without panics, use [`Timestamp::checked_sub`]. Note that the failure
2444/// condition includes overflow and using a `Span` with non-zero units greater
2445/// than hours.
2446impl core::ops::SubAssign<Span> for Timestamp {
2447 #[inline]
2448 fn sub_assign(&mut self, rhs: Span) {
2449 *self = *self - rhs
2450 }
2451}
2452
2453/// Computes the span of time between two timestamps.
2454///
2455/// This will return a negative duration when the timestamp being subtracted is
2456/// greater.
2457///
2458/// To get a [`Span`] or configure the largest unit or enable rounding, use
2459/// [`Timestamp::since`].
2460impl core::ops::Sub for Timestamp {
2461 type Output = SignedDuration;
2462
2463 #[inline]
2464 fn sub(self, rhs: Timestamp) -> SignedDuration {
2465 self.duration_since(rhs)
2466 }
2467}
2468
2469/// Adds a signed duration of time to a timestamp.
2470///
2471/// This uses checked arithmetic and panics on overflow. To handle overflow
2472/// without panics, use [`Timestamp::checked_add`].
2473impl core::ops::Add<SignedDuration> for Timestamp {
2474 type Output = Timestamp;
2475
2476 #[inline]
2477 fn add(self, rhs: SignedDuration) -> Timestamp {
2478 self.checked_add_duration(rhs)
2479 .expect("adding signed duration to timestamp overflowed")
2480 }
2481}
2482
2483/// Adds a signed duration of time to a timestamp in place.
2484///
2485/// This uses checked arithmetic and panics on overflow. To handle overflow
2486/// without panics, use [`Timestamp::checked_add`].
2487impl core::ops::AddAssign<SignedDuration> for Timestamp {
2488 #[inline]
2489 fn add_assign(&mut self, rhs: SignedDuration) {
2490 *self = *self + rhs
2491 }
2492}
2493
2494/// Subtracts a signed duration of time from a timestamp.
2495///
2496/// This uses checked arithmetic and panics on overflow. To handle overflow
2497/// without panics, use [`Timestamp::checked_sub`].
2498impl core::ops::Sub<SignedDuration> for Timestamp {
2499 type Output = Timestamp;
2500
2501 #[inline]
2502 fn sub(self, rhs: SignedDuration) -> Timestamp {
2503 let rhs = rhs
2504 .checked_neg()
2505 .expect("signed duration negation resulted in overflow");
2506 self.checked_add_duration(rhs)
2507 .expect("subtracting signed duration from timestamp overflowed")
2508 }
2509}
2510
2511/// Subtracts a signed duration of time from a timestamp in place.
2512///
2513/// This uses checked arithmetic and panics on overflow. To handle overflow
2514/// without panics, use [`Timestamp::checked_sub`].
2515impl core::ops::SubAssign<SignedDuration> for Timestamp {
2516 #[inline]
2517 fn sub_assign(&mut self, rhs: SignedDuration) {
2518 *self = *self - rhs
2519 }
2520}
2521
2522/// Adds an unsigned duration of time to a timestamp.
2523///
2524/// This uses checked arithmetic and panics on overflow. To handle overflow
2525/// without panics, use [`Timestamp::checked_add`].
2526impl core::ops::Add<UnsignedDuration> for Timestamp {
2527 type Output = Timestamp;
2528
2529 #[inline]
2530 fn add(self, rhs: UnsignedDuration) -> Timestamp {
2531 self.checked_add(rhs)
2532 .expect("adding unsigned duration to timestamp overflowed")
2533 }
2534}
2535
2536/// Adds an unsigned duration of time to a timestamp in place.
2537///
2538/// This uses checked arithmetic and panics on overflow. To handle overflow
2539/// without panics, use [`Timestamp::checked_add`].
2540impl core::ops::AddAssign<UnsignedDuration> for Timestamp {
2541 #[inline]
2542 fn add_assign(&mut self, rhs: UnsignedDuration) {
2543 *self = *self + rhs
2544 }
2545}
2546
2547/// Subtracts an unsigned duration of time from a timestamp.
2548///
2549/// This uses checked arithmetic and panics on overflow. To handle overflow
2550/// without panics, use [`Timestamp::checked_sub`].
2551impl core::ops::Sub<UnsignedDuration> for Timestamp {
2552 type Output = Timestamp;
2553
2554 #[inline]
2555 fn sub(self, rhs: UnsignedDuration) -> Timestamp {
2556 self.checked_sub(rhs)
2557 .expect("subtracting unsigned duration from timestamp overflowed")
2558 }
2559}
2560
2561/// Subtracts an unsigned duration of time from a timestamp in place.
2562///
2563/// This uses checked arithmetic and panics on overflow. To handle overflow
2564/// without panics, use [`Timestamp::checked_sub`].
2565impl core::ops::SubAssign<UnsignedDuration> for Timestamp {
2566 #[inline]
2567 fn sub_assign(&mut self, rhs: UnsignedDuration) {
2568 *self = *self - rhs
2569 }
2570}
2571
2572impl From<ZonedDateTime> for Timestamp {
2573 #[inline]
2574 fn from(zdt: ZonedDateTime) -> Timestamp {
2575 zdt.timestamp()
2576 }
2577}
2578
2579impl<'a> From<&'a ZonedDateTime> for Timestamp {
2580 #[inline]
2581 fn from(zdt: &'a ZonedDateTime) -> Timestamp {
2582 zdt.timestamp()
2583 }
2584}
2585
2586/// Converts a timestamp to a system time.
2587///
2588/// The precision of a system time depends on the platform. This conversion
2589/// may truncate the subsecond precision of the timestamp.
2590///
2591/// # Errors
2592///
2593/// This returns an error when the timestamp is outside the range supported
2594/// by `SystemTime` on the current platform.
2595///
2596/// # Example
2597///
2598/// ```
2599/// use std::time::SystemTime;
2600/// use jiff::Timestamp;
2601///
2602/// let timestamp: Timestamp = "2025-12-30T15:29:46Z".parse()?;
2603/// let system_time = SystemTime::try_from(timestamp)?;
2604/// assert_eq!(Timestamp::try_from(system_time)?, timestamp);
2605///
2606/// # Ok::<(), Box<dyn std::error::Error>>(())
2607/// ```
2608#[cfg(feature = "std")]
2609impl TryFrom<Timestamp> for std::time::SystemTime {
2610 type Error = Error;
2611
2612 #[inline]
2613 fn try_from(time: Timestamp) -> Result<std::time::SystemTime, Error> {
2614 let unix_epoch = std::time::SystemTime::UNIX_EPOCH;
2615 let sdur = time.as_duration();
2616 let dur = sdur.unsigned_abs();
2617 let system_time = if sdur.is_negative() {
2618 unix_epoch.checked_sub(dur)
2619 } else {
2620 unix_epoch.checked_add(dur)
2621 };
2622 system_time
2623 .ok_or_else(|| E::ConvertToSystemTime { timestamp: time }.into())
2624 }
2625}
2626
2627#[cfg(feature = "std")]
2628impl TryFrom<std::time::SystemTime> for Timestamp {
2629 type Error = Error;
2630
2631 #[inline]
2632 fn try_from(
2633 system_time: std::time::SystemTime,
2634 ) -> Result<Timestamp, Error> {
2635 let unix_epoch = std::time::SystemTime::UNIX_EPOCH;
2636 let dur = SignedDuration::system_until(unix_epoch, system_time)?;
2637 Timestamp::from_duration(dur)
2638 }
2639}
2640
2641#[cfg(feature = "defmt")]
2642impl defmt::Format for Timestamp {
2643 fn format(&self, f: defmt::Formatter) {
2644 use crate::fmt::{DefmtWrite, temporal::DEFAULT_DATETIME_PRINTER};
2645
2646 defmt::unwrap!(
2647 DEFAULT_DATETIME_PRINTER.print_timestamp(self, DefmtWrite(f))
2648 );
2649 }
2650}
2651
2652#[cfg(feature = "serde")]
2653impl serde_core::Serialize for Timestamp {
2654 #[inline]
2655 fn serialize<S: serde_core::Serializer>(
2656 &self,
2657 serializer: S,
2658 ) -> Result<S::Ok, S::Error> {
2659 serializer.collect_str(self)
2660 }
2661}
2662
2663#[cfg(feature = "serde")]
2664impl<'de> serde_core::Deserialize<'de> for Timestamp {
2665 #[inline]
2666 fn deserialize<D: serde_core::Deserializer<'de>>(
2667 deserializer: D,
2668 ) -> Result<Timestamp, D::Error> {
2669 use serde_core::de;
2670
2671 struct TimestampVisitor;
2672
2673 impl<'de> de::Visitor<'de> for TimestampVisitor {
2674 type Value = Timestamp;
2675
2676 fn expecting(
2677 &self,
2678 f: &mut core::fmt::Formatter,
2679 ) -> core::fmt::Result {
2680 f.write_str("a timestamp string")
2681 }
2682
2683 #[inline]
2684 fn visit_bytes<E: de::Error>(
2685 self,
2686 value: &[u8],
2687 ) -> Result<Timestamp, E> {
2688 DEFAULT_DATETIME_PARSER
2689 .parse_timestamp(value)
2690 .map_err(de::Error::custom)
2691 }
2692
2693 #[inline]
2694 fn visit_str<E: de::Error>(
2695 self,
2696 value: &str,
2697 ) -> Result<Timestamp, E> {
2698 self.visit_bytes(value.as_bytes())
2699 }
2700 }
2701
2702 deserializer.deserialize_str(TimestampVisitor)
2703 }
2704}
2705
2706#[cfg(test)]
2707impl quickcheck::Arbitrary for Timestamp {
2708 fn arbitrary(g: &mut quickcheck::Gen) -> Timestamp {
2709 use crate::util::b;
2710
2711 let secs = b::UnixEpochSeconds::arbitrary(g);
2712 let mut nanos = b::SignedSubsecNanosecond::arbitrary(g);
2713 // nanoseconds must be zero for the minimum second value,
2714 // so just clamp it to 0.
2715 if secs == b::UnixEpochSeconds::MIN && nanos < 0 {
2716 nanos = 0;
2717 }
2718 Timestamp::new(secs, nanos).unwrap_or_default()
2719 }
2720
2721 fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
2722 use crate::util::b;
2723
2724 let secs = self.as_second();
2725 let nanos = self.subsec_nanosecond();
2726 alloc::boxed::Box::new((secs, nanos).shrink().filter_map(
2727 |(secs, nanos)| {
2728 let secs = b::UnixEpochSeconds::check(secs).ok()?;
2729 let nanos = b::SignedSubsecNanosecond::check(nanos).ok()?;
2730 if secs == b::UnixEpochSeconds::MIN && nanos > 0 {
2731 None
2732 } else {
2733 Timestamp::new(secs, nanos).ok()
2734 }
2735 },
2736 ))
2737 }
2738}
2739
2740/// A type for formatting a [`Timestamp`] with a specific offset.
2741///
2742/// This type is created by the [`Timestamp::display_with_offset`] method.
2743///
2744/// Like the [`std::fmt::Display`] trait implementation for `Timestamp`, this
2745/// always emits an RFC 3339 compliant string. Unlike `Timestamp`'s `Display`
2746/// trait implementation, which always uses `Z` or "Zulu" time, this always
2747/// uses an offset.
2748///
2749/// # Formatting options supported
2750///
2751/// * [`std::fmt::Formatter::precision`] can be set to control the precision
2752/// of the fractional second component.
2753///
2754/// # Example
2755///
2756/// ```
2757/// use jiff::{tz, Timestamp};
2758///
2759/// let offset = tz::offset(-5);
2760/// let ts = Timestamp::new(1_123_456_789, 123_000_000)?;
2761/// assert_eq!(
2762/// format!("{ts:.6}", ts = ts.display_with_offset(offset)),
2763/// "2005-08-07T18:19:49.123000-05:00",
2764/// );
2765/// // Precision values greater than 9 are clamped to 9.
2766/// assert_eq!(
2767/// format!("{ts:.300}", ts = ts.display_with_offset(offset)),
2768/// "2005-08-07T18:19:49.123000000-05:00",
2769/// );
2770/// // A precision of 0 implies the entire fractional
2771/// // component is always truncated.
2772/// assert_eq!(
2773/// format!("{ts:.0}", ts = ts.display_with_offset(tz::Offset::UTC)),
2774/// "2005-08-07T23:19:49+00:00",
2775/// );
2776///
2777/// # Ok::<(), Box<dyn std::error::Error>>(())
2778/// ```
2779#[derive(Clone, Copy, Debug)]
2780pub struct TimestampDisplayWithOffset {
2781 timestamp: Timestamp,
2782 offset: Offset,
2783}
2784
2785impl core::fmt::Display for TimestampDisplayWithOffset {
2786 #[inline]
2787 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2788 use crate::fmt::StdFmtWrite;
2789
2790 let precision =
2791 f.precision().map(|p| u8::try_from(p).unwrap_or(u8::MAX));
2792 temporal::DateTimePrinter::new()
2793 .precision(precision)
2794 .print_timestamp_with_offset(
2795 &self.timestamp,
2796 self.offset,
2797 StdFmtWrite(f),
2798 )
2799 .map_err(|_| core::fmt::Error)
2800 }
2801}
2802
2803/// An iterator over periodic timestamps, created by [`Timestamp::series`].
2804///
2805/// It is exhausted when the next value would exceed the limits of a [`Span`]
2806/// or [`Timestamp`] value.
2807///
2808/// This iterator is created by [`Timestamp::series`].
2809#[derive(Clone, Debug)]
2810pub struct TimestampSeries {
2811 ts: Timestamp,
2812 duration: Option<SignedDuration>,
2813}
2814
2815impl TimestampSeries {
2816 #[inline]
2817 fn new(ts: Timestamp, period: Span) -> TimestampSeries {
2818 let duration = SignedDuration::try_from(period).ok();
2819 TimestampSeries { ts, duration }
2820 }
2821}
2822
2823impl Iterator for TimestampSeries {
2824 type Item = Timestamp;
2825
2826 #[inline]
2827 fn next(&mut self) -> Option<Timestamp> {
2828 let duration = self.duration?;
2829 let this = self.ts;
2830 self.ts = self.ts.checked_add_duration(duration).ok()?;
2831 Some(this)
2832 }
2833}
2834
2835impl core::iter::FusedIterator for TimestampSeries {}
2836
2837/// Options for [`Timestamp::checked_add`] and [`Timestamp::checked_sub`].
2838///
2839/// This type provides a way to ergonomically add one of a few different
2840/// duration types to a [`Timestamp`].
2841///
2842/// The main way to construct values of this type is with its `From` trait
2843/// implementations:
2844///
2845/// * `From<Span> for TimestampArithmetic` adds (or subtracts) the given span
2846/// to the receiver timestamp.
2847/// * `From<SignedDuration> for TimestampArithmetic` adds (or subtracts)
2848/// the given signed duration to the receiver timestamp.
2849/// * `From<std::time::Duration> for TimestampArithmetic` adds (or subtracts)
2850/// the given unsigned duration to the receiver timestamp.
2851///
2852/// # Example
2853///
2854/// ```
2855/// use std::time::Duration;
2856///
2857/// use jiff::{SignedDuration, Timestamp, ToSpan};
2858///
2859/// let ts: Timestamp = "2024-02-28T00:00:00Z".parse()?;
2860/// assert_eq!(
2861/// ts.checked_add(48.hours())?,
2862/// "2024-03-01T00:00:00Z".parse()?,
2863/// );
2864/// assert_eq!(
2865/// ts.checked_add(SignedDuration::from_hours(48))?,
2866/// "2024-03-01T00:00:00Z".parse()?,
2867/// );
2868/// assert_eq!(
2869/// ts.checked_add(Duration::from_secs(48 * 60 * 60))?,
2870/// "2024-03-01T00:00:00Z".parse()?,
2871/// );
2872///
2873/// # Ok::<(), Box<dyn std::error::Error>>(())
2874/// ```
2875#[derive(Clone, Copy, Debug)]
2876pub struct TimestampArithmetic {
2877 duration: Duration,
2878}
2879
2880impl TimestampArithmetic {
2881 #[inline]
2882 fn checked_add(self, ts: Timestamp) -> Result<Timestamp, Error> {
2883 match self.duration.to_signed()? {
2884 SDuration::Span(span) => ts.checked_add_span(span),
2885 SDuration::Absolute(sdur) => ts.checked_add_duration(sdur),
2886 }
2887 }
2888
2889 #[inline]
2890 fn saturating_add(self, ts: Timestamp) -> Result<Timestamp, Error> {
2891 let Ok(signed) = self.duration.to_signed() else {
2892 return Ok(Timestamp::MAX);
2893 };
2894 let result = match signed {
2895 SDuration::Span(span) => {
2896 if let Some(err) = span.smallest_non_time_non_zero_unit_error()
2897 {
2898 return Err(err);
2899 }
2900 ts.checked_add_span(span)
2901 }
2902 SDuration::Absolute(sdur) => ts.checked_add_duration(sdur),
2903 };
2904 Ok(result.unwrap_or_else(|_| {
2905 if self.is_negative() { Timestamp::MIN } else { Timestamp::MAX }
2906 }))
2907 }
2908
2909 #[inline]
2910 fn checked_neg(self) -> Result<TimestampArithmetic, Error> {
2911 let duration = self.duration.checked_neg()?;
2912 Ok(TimestampArithmetic { duration })
2913 }
2914
2915 #[inline]
2916 fn is_negative(&self) -> bool {
2917 self.duration.is_negative()
2918 }
2919}
2920
2921impl From<Span> for TimestampArithmetic {
2922 fn from(span: Span) -> TimestampArithmetic {
2923 let duration = Duration::from(span);
2924 TimestampArithmetic { duration }
2925 }
2926}
2927
2928impl From<SignedDuration> for TimestampArithmetic {
2929 fn from(sdur: SignedDuration) -> TimestampArithmetic {
2930 let duration = Duration::from(sdur);
2931 TimestampArithmetic { duration }
2932 }
2933}
2934
2935impl From<UnsignedDuration> for TimestampArithmetic {
2936 fn from(udur: UnsignedDuration) -> TimestampArithmetic {
2937 let duration = Duration::from(udur);
2938 TimestampArithmetic { duration }
2939 }
2940}
2941
2942impl<'a> From<&'a Span> for TimestampArithmetic {
2943 fn from(span: &'a Span) -> TimestampArithmetic {
2944 TimestampArithmetic::from(*span)
2945 }
2946}
2947
2948impl<'a> From<&'a SignedDuration> for TimestampArithmetic {
2949 fn from(sdur: &'a SignedDuration) -> TimestampArithmetic {
2950 TimestampArithmetic::from(*sdur)
2951 }
2952}
2953
2954impl<'a> From<&'a UnsignedDuration> for TimestampArithmetic {
2955 fn from(udur: &'a UnsignedDuration) -> TimestampArithmetic {
2956 TimestampArithmetic::from(*udur)
2957 }
2958}
2959
2960/// Options for [`Timestamp::since`] and [`Timestamp::until`].
2961///
2962/// This type provides a way to configure the calculation of
2963/// spans between two [`Timestamp`] values. In particular, both
2964/// `Timestamp::since` and `Timestamp::until` accept anything that implements
2965/// `Into<TimestampDifference>`. There are a few key trait implementations that
2966/// make this convenient:
2967///
2968/// * `From<Timestamp> for TimestampDifference` will construct a
2969/// configuration consisting of just the timestamp. So for example,
2970/// `timestamp1.until(timestamp2)` will return the span from `timestamp1` to
2971/// `timestamp2`.
2972/// * `From<ZonedDateTime> for TimestampDifference` will construct a
2973/// configuration consisting of the timestamp from the given zoned datetime. So
2974/// for example, `timestamp.since(zoned)` returns the span from
2975/// `zoned.to_timestamp()` to `timestamp`.
2976/// * `From<(Unit, Timestamp)>` is a convenient way to specify the largest
2977/// units that should be present on the span returned. By default, the largest
2978/// units are seconds. Using this trait implementation is equivalent to
2979/// `TimestampDifference::new(timestamp).largest(unit)`.
2980/// * `From<(Unit, ZonedDateTime)>` is like the one above, but with the time
2981/// from the given zoned datetime.
2982///
2983/// One can also provide a `TimestampDifference` value directly. Doing so
2984/// is necessary to use the rounding features of calculating a span. For
2985/// example, setting the smallest unit (defaults to [`Unit::Nanosecond`]), the
2986/// rounding mode (defaults to [`RoundMode::Trunc`]) and the rounding increment
2987/// (defaults to `1`). The defaults are selected such that no rounding occurs.
2988///
2989/// Rounding a span as part of calculating it is provided as a convenience.
2990/// Callers may choose to round the span as a distinct step via
2991/// [`Span::round`].
2992///
2993/// # Example
2994///
2995/// This example shows how to round a span between two timestamps to the
2996/// nearest half-hour, with ties breaking away from zero.
2997///
2998/// ```
2999/// use jiff::{RoundMode, Timestamp, TimestampDifference, ToSpan, Unit};
3000///
3001/// let ts1 = "2024-03-15 08:14:00.123456789Z".parse::<Timestamp>()?;
3002/// let ts2 = "2024-03-22 15:00Z".parse::<Timestamp>()?;
3003/// let span = ts1.until(
3004/// TimestampDifference::new(ts2)
3005/// .smallest(Unit::Minute)
3006/// .largest(Unit::Hour)
3007/// .mode(RoundMode::HalfExpand)
3008/// .increment(30),
3009/// )?;
3010/// assert_eq!(format!("{span:#}"), "175h");
3011///
3012/// // One less minute, and because of the HalfExpand mode, the span would
3013/// // get rounded down.
3014/// let ts2 = "2024-03-22 14:59Z".parse::<Timestamp>()?;
3015/// let span = ts1.until(
3016/// TimestampDifference::new(ts2)
3017/// .smallest(Unit::Minute)
3018/// .largest(Unit::Hour)
3019/// .mode(RoundMode::HalfExpand)
3020/// .increment(30),
3021/// )?;
3022/// assert_eq!(span, 174.hours().minutes(30).fieldwise());
3023///
3024/// # Ok::<(), Box<dyn std::error::Error>>(())
3025/// ```
3026#[derive(Clone, Copy, Debug)]
3027pub struct TimestampDifference {
3028 timestamp: Timestamp,
3029 round: SpanRound<'static>,
3030}
3031
3032impl TimestampDifference {
3033 /// Create a new default configuration for computing the span between
3034 /// the given timestamp and some other time (specified as the receiver in
3035 /// [`Timestamp::since`] or [`Timestamp::until`]).
3036 #[inline]
3037 pub fn new(timestamp: Timestamp) -> TimestampDifference {
3038 // We use truncation rounding by default since it seems that's
3039 // what is generally expected when computing the difference between
3040 // datetimes.
3041 //
3042 // See: https://github.com/tc39/proposal-temporal/issues/1122
3043 let round = SpanRound::new().mode(RoundMode::Trunc);
3044 TimestampDifference { timestamp, round }
3045 }
3046
3047 /// Set the smallest units allowed in the span returned.
3048 ///
3049 /// # Errors
3050 ///
3051 /// The smallest units must be no greater than the largest units. If this
3052 /// is violated, then computing a span with this configuration will result
3053 /// in an error.
3054 ///
3055 /// The largest unit must also be no greater than `Unit::Hour`.
3056 ///
3057 /// # Example
3058 ///
3059 /// This shows how to round a span between two timestamps to units no less
3060 /// than seconds.
3061 ///
3062 /// ```
3063 /// use jiff::{RoundMode, Timestamp, TimestampDifference, ToSpan, Unit};
3064 ///
3065 /// let ts1 = "2024-03-15 08:14:02.5001Z".parse::<Timestamp>()?;
3066 /// let ts2 = "2024-03-15T08:16:03.0001Z".parse::<Timestamp>()?;
3067 /// let span = ts1.until(
3068 /// TimestampDifference::new(ts2)
3069 /// .smallest(Unit::Second)
3070 /// .mode(RoundMode::HalfExpand),
3071 /// )?;
3072 /// assert_eq!(span, 121.seconds().fieldwise());
3073 ///
3074 /// // Because of the rounding mode, a small less-than-1-second increase in
3075 /// // the first timestamp can change the result of rounding.
3076 /// let ts1 = "2024-03-15 08:14:02.5002Z".parse::<Timestamp>()?;
3077 /// let span = ts1.until(
3078 /// TimestampDifference::new(ts2)
3079 /// .smallest(Unit::Second)
3080 /// .mode(RoundMode::HalfExpand),
3081 /// )?;
3082 /// assert_eq!(span, 120.seconds().fieldwise());
3083 ///
3084 /// # Ok::<(), Box<dyn std::error::Error>>(())
3085 /// ```
3086 #[inline]
3087 pub fn smallest(self, unit: Unit) -> TimestampDifference {
3088 TimestampDifference { round: self.round.smallest(unit), ..self }
3089 }
3090
3091 /// Set the largest units allowed in the span returned.
3092 ///
3093 /// When a largest unit is not specified, computing a span between
3094 /// timestamps behaves as if it were set to [`Unit::Second`]. Unless
3095 /// [`TimestampDifference::smallest`] is bigger than `Unit::Second`, then
3096 /// the largest unit is set to the smallest unit.
3097 ///
3098 /// # Errors
3099 ///
3100 /// The largest units, when set, must be at least as big as the smallest
3101 /// units (which defaults to [`Unit::Nanosecond`]). If this is violated,
3102 /// then computing a span with this configuration will result in an error.
3103 ///
3104 /// The largest unit must also be no greater than `Unit::Hour`.
3105 ///
3106 /// # Example
3107 ///
3108 /// This shows how to round a span between two timestamps to units no
3109 /// bigger than seconds.
3110 ///
3111 /// ```
3112 /// use jiff::{Timestamp, TimestampDifference, ToSpan, Unit};
3113 ///
3114 /// let ts1 = "2024-03-15 08:14Z".parse::<Timestamp>()?;
3115 /// let ts2 = "2030-11-22 08:30Z".parse::<Timestamp>()?;
3116 /// let span = ts1.until(
3117 /// TimestampDifference::new(ts2).largest(Unit::Second),
3118 /// )?;
3119 /// assert_eq!(format!("{span:#}"), "211076160s");
3120 ///
3121 /// # Ok::<(), Box<dyn std::error::Error>>(())
3122 /// ```
3123 #[inline]
3124 pub fn largest(self, unit: Unit) -> TimestampDifference {
3125 TimestampDifference { round: self.round.largest(unit), ..self }
3126 }
3127
3128 /// Set the rounding mode.
3129 ///
3130 /// This defaults to [`RoundMode::Trunc`] since it's plausible that
3131 /// rounding "up" in the context of computing the span between
3132 /// two timestamps could be surprising in a number of cases. The
3133 /// [`RoundMode::HalfExpand`] mode corresponds to typical rounding you
3134 /// might have learned about in school. But a variety of other rounding
3135 /// modes exist.
3136 ///
3137 /// # Example
3138 ///
3139 /// This shows how to always round "up" towards positive infinity.
3140 ///
3141 /// ```
3142 /// use jiff::{RoundMode, Timestamp, TimestampDifference, ToSpan, Unit};
3143 ///
3144 /// let ts1 = "2024-03-15 08:10Z".parse::<Timestamp>()?;
3145 /// let ts2 = "2024-03-15 08:11Z".parse::<Timestamp>()?;
3146 /// let span = ts1.until(
3147 /// TimestampDifference::new(ts2)
3148 /// .smallest(Unit::Hour)
3149 /// .mode(RoundMode::Ceil),
3150 /// )?;
3151 /// // Only one minute elapsed, but we asked to always round up!
3152 /// assert_eq!(span, 1.hour().fieldwise());
3153 ///
3154 /// // Since `Ceil` always rounds toward positive infinity, the behavior
3155 /// // flips for a negative span.
3156 /// let span = ts1.since(
3157 /// TimestampDifference::new(ts2)
3158 /// .smallest(Unit::Hour)
3159 /// .mode(RoundMode::Ceil),
3160 /// )?;
3161 /// assert_eq!(span, 0.hour().fieldwise());
3162 ///
3163 /// # Ok::<(), Box<dyn std::error::Error>>(())
3164 /// ```
3165 #[inline]
3166 pub fn mode(self, mode: RoundMode) -> TimestampDifference {
3167 TimestampDifference { round: self.round.mode(mode), ..self }
3168 }
3169
3170 /// Set the rounding increment for the smallest unit.
3171 ///
3172 /// The default value is `1`. Other values permit rounding the smallest
3173 /// unit to the nearest integer increment specified. For example, if the
3174 /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
3175 /// `30` would result in rounding in increments of a half hour. That is,
3176 /// the only minute value that could result would be `0` or `30`.
3177 ///
3178 /// # Errors
3179 ///
3180 /// The rounding increment must divide evenly into the next highest unit
3181 /// after the smallest unit configured (and must not be equivalent to it).
3182 /// For example, if the smallest unit is [`Unit::Nanosecond`], then *some*
3183 /// of the valid values for the rounding increment are `1`, `2`, `4`, `5`,
3184 /// `100` and `500`. Namely, any integer that divides evenly into `1,000`
3185 /// nanoseconds since there are `1,000` nanoseconds in the next highest
3186 /// unit (microseconds).
3187 ///
3188 /// In all cases, the increment must be greater than zero and less than or
3189 /// equal to `1_000_000_000`.
3190 ///
3191 /// The error will occur when computing the span, and not when setting
3192 /// the increment here.
3193 ///
3194 /// # Example
3195 ///
3196 /// This shows how to round the span between two timestamps to the nearest
3197 /// 5 minute increment.
3198 ///
3199 /// ```
3200 /// use jiff::{RoundMode, Timestamp, TimestampDifference, ToSpan, Unit};
3201 ///
3202 /// let ts1 = "2024-03-15 08:19Z".parse::<Timestamp>()?;
3203 /// let ts2 = "2024-03-15 12:52Z".parse::<Timestamp>()?;
3204 /// let span = ts1.until(
3205 /// TimestampDifference::new(ts2)
3206 /// .smallest(Unit::Minute)
3207 /// .increment(5)
3208 /// .mode(RoundMode::HalfExpand),
3209 /// )?;
3210 /// assert_eq!(span.to_string(), "PT275M");
3211 ///
3212 /// # Ok::<(), Box<dyn std::error::Error>>(())
3213 /// ```
3214 #[inline]
3215 pub fn increment(self, increment: i64) -> TimestampDifference {
3216 TimestampDifference { round: self.round.increment(increment), ..self }
3217 }
3218
3219 /// Returns true if and only if this configuration could change the span
3220 /// via rounding.
3221 #[inline]
3222 fn rounding_may_change_span(&self) -> bool {
3223 self.round.rounding_may_change_span()
3224 }
3225
3226 /// Returns the span of time from `ts1` to the timestamp in this
3227 /// configuration. The biggest units allowed are determined by the
3228 /// `smallest` and `largest` settings, but defaults to `Unit::Second`.
3229 #[inline]
3230 fn until_with_largest_unit(&self, t1: Timestamp) -> Result<Span, Error> {
3231 let t2 = self.timestamp;
3232 let largest = self
3233 .round
3234 .get_largest()
3235 .unwrap_or_else(|| self.round.get_smallest().max(Unit::Second));
3236 if largest >= Unit::Day {
3237 return Err(Error::from(
3238 UnitConfigError::RoundToUnitUnsupported { unit: largest },
3239 ));
3240 }
3241
3242 let diff = t2.as_duration() - t1.as_duration();
3243 // This can fail when `largest` is nanoseconds since not all intervals
3244 // can be represented by a single i64 in units of nanoseconds.
3245 Span::from_invariant_duration(largest, diff)
3246 }
3247}
3248
3249impl From<Timestamp> for TimestampDifference {
3250 #[inline]
3251 fn from(ts: Timestamp) -> TimestampDifference {
3252 TimestampDifference::new(ts)
3253 }
3254}
3255
3256impl From<ZonedDateTime> for TimestampDifference {
3257 #[inline]
3258 fn from(zdt: ZonedDateTime) -> TimestampDifference {
3259 TimestampDifference::new(Timestamp::from(zdt))
3260 }
3261}
3262
3263impl<'a> From<&'a ZonedDateTime> for TimestampDifference {
3264 #[inline]
3265 fn from(zdt: &'a ZonedDateTime) -> TimestampDifference {
3266 TimestampDifference::from(Timestamp::from(zdt))
3267 }
3268}
3269
3270impl From<(Unit, Timestamp)> for TimestampDifference {
3271 #[inline]
3272 fn from((largest, ts): (Unit, Timestamp)) -> TimestampDifference {
3273 TimestampDifference::from(ts).largest(largest)
3274 }
3275}
3276
3277impl From<(Unit, ZonedDateTime)> for TimestampDifference {
3278 #[inline]
3279 fn from((largest, zdt): (Unit, ZonedDateTime)) -> TimestampDifference {
3280 TimestampDifference::from((largest, Timestamp::from(zdt)))
3281 }
3282}
3283
3284impl<'a> From<(Unit, &'a ZonedDateTime)> for TimestampDifference {
3285 #[inline]
3286 fn from((largest, zdt): (Unit, &'a ZonedDateTime)) -> TimestampDifference {
3287 TimestampDifference::from((largest, Timestamp::from(zdt)))
3288 }
3289}
3290
3291/// Options for [`Timestamp::round`].
3292///
3293/// This type provides a way to configure the rounding of a timestamp. In
3294/// particular, `Timestamp::round` accepts anything that implements the
3295/// `Into<TimestampRound>` trait. There are some trait implementations that
3296/// therefore make calling `Timestamp::round` in some common cases more
3297/// ergonomic:
3298///
3299/// * `From<Unit> for TimestampRound` will construct a rounding
3300/// configuration that rounds to the unit given. Specifically,
3301/// `TimestampRound::new().smallest(unit)`.
3302/// * `From<(Unit, i64)> for TimestampRound` is like the one above, but also
3303/// specifies the rounding increment for [`TimestampRound::increment`].
3304///
3305/// Note that in the default configuration, no rounding occurs.
3306///
3307/// # Example
3308///
3309/// This example shows how to round a timestamp to the nearest second:
3310///
3311/// ```
3312/// use jiff::{Timestamp, Unit};
3313///
3314/// let ts: Timestamp = "2024-06-20 16:24:59.5Z".parse()?;
3315/// assert_eq!(
3316/// ts.round(Unit::Second)?.to_string(),
3317/// // The second rounds up and causes minutes to increase.
3318/// "2024-06-20T16:25:00Z",
3319/// );
3320///
3321/// # Ok::<(), Box<dyn std::error::Error>>(())
3322/// ```
3323///
3324/// The above makes use of the fact that `Unit` implements
3325/// `Into<TimestampRound>`. If you want to change the rounding mode to, say,
3326/// truncation, then you'll need to construct a `TimestampRound` explicitly
3327/// since there are no convenience `Into` trait implementations for
3328/// [`RoundMode`].
3329///
3330/// ```
3331/// use jiff::{RoundMode, Timestamp, TimestampRound, Unit};
3332///
3333/// let ts: Timestamp = "2024-06-20 16:24:59.5Z".parse()?;
3334/// assert_eq!(
3335/// ts.round(
3336/// TimestampRound::new().smallest(Unit::Second).mode(RoundMode::Trunc),
3337/// )?.to_string(),
3338/// // The second just gets truncated as if it wasn't there.
3339/// "2024-06-20T16:24:59Z",
3340/// );
3341///
3342/// # Ok::<(), Box<dyn std::error::Error>>(())
3343/// ```
3344#[derive(Clone, Copy, Debug)]
3345pub struct TimestampRound {
3346 smallest: Unit,
3347 mode: RoundMode,
3348 increment: i64,
3349}
3350
3351impl TimestampRound {
3352 /// Create a new default configuration for rounding a [`Timestamp`].
3353 #[inline]
3354 pub fn new() -> TimestampRound {
3355 TimestampRound {
3356 smallest: Unit::Nanosecond,
3357 mode: RoundMode::HalfExpand,
3358 increment: 1,
3359 }
3360 }
3361
3362 /// Set the smallest units allowed in the timestamp returned after
3363 /// rounding.
3364 ///
3365 /// Any units below the smallest configured unit will be used, along with
3366 /// the rounding increment and rounding mode, to determine the value of the
3367 /// smallest unit. For example, when rounding `2024-06-20T03:25:30Z` to the
3368 /// nearest minute, the `30` second unit will result in rounding the minute
3369 /// unit of `25` up to `26` and zeroing out everything below minutes.
3370 ///
3371 /// This defaults to [`Unit::Nanosecond`].
3372 ///
3373 /// # Errors
3374 ///
3375 /// The smallest units must be no greater than [`Unit::Hour`].
3376 ///
3377 /// # Example
3378 ///
3379 /// ```
3380 /// use jiff::{Timestamp, TimestampRound, Unit};
3381 ///
3382 /// let ts: Timestamp = "2024-06-20T03:25:30Z".parse()?;
3383 /// assert_eq!(
3384 /// ts.round(TimestampRound::new().smallest(Unit::Minute))?.to_string(),
3385 /// "2024-06-20T03:26:00Z",
3386 /// );
3387 /// // Or, utilize the `From<Unit> for TimestampRound` impl:
3388 /// assert_eq!(
3389 /// ts.round(Unit::Minute)?.to_string(),
3390 /// "2024-06-20T03:26:00Z",
3391 /// );
3392 ///
3393 /// # Ok::<(), Box<dyn std::error::Error>>(())
3394 /// ```
3395 #[inline]
3396 pub fn smallest(self, unit: Unit) -> TimestampRound {
3397 TimestampRound { smallest: unit, ..self }
3398 }
3399
3400 /// Set the rounding mode.
3401 ///
3402 /// This defaults to [`RoundMode::HalfExpand`], which rounds away from
3403 /// zero. It matches the kind of rounding you might have been taught in
3404 /// school.
3405 ///
3406 /// # Example
3407 ///
3408 /// This shows how to always round timestamps up towards positive infinity.
3409 ///
3410 /// ```
3411 /// use jiff::{RoundMode, Timestamp, TimestampRound, Unit};
3412 ///
3413 /// let ts: Timestamp = "2024-06-20 03:25:01Z".parse()?;
3414 /// assert_eq!(
3415 /// ts.round(
3416 /// TimestampRound::new()
3417 /// .smallest(Unit::Minute)
3418 /// .mode(RoundMode::Ceil),
3419 /// )?.to_string(),
3420 /// "2024-06-20T03:26:00Z",
3421 /// );
3422 ///
3423 /// # Ok::<(), Box<dyn std::error::Error>>(())
3424 /// ```
3425 #[inline]
3426 pub fn mode(self, mode: RoundMode) -> TimestampRound {
3427 TimestampRound { mode, ..self }
3428 }
3429
3430 /// Set the rounding increment for the smallest unit.
3431 ///
3432 /// The default value is `1`. Other values permit rounding the smallest
3433 /// unit to the nearest integer increment specified. For example, if the
3434 /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
3435 /// `30` would result in rounding in increments of a half hour. That is,
3436 /// the only minute value that could result would be `0` or `30`.
3437 ///
3438 /// # Errors
3439 ///
3440 /// The rounding increment, when combined with the smallest unit (which
3441 /// defaults to [`Unit::Nanosecond`]), must divide evenly into `86,400`
3442 /// seconds (one 24-hour civil day). For example, increments of both
3443 /// 45 seconds and 15 minutes are allowed, but 7 seconds and 25 minutes are
3444 /// both not allowed.
3445 ///
3446 /// In all cases, the increment must be greater than zero and less than or
3447 /// equal to `1_000_000_000`. Note that this means, for example, one
3448 /// cannot round to the nearest `43_200_000_000_000` nanosecond, despite
3449 /// the fact that it divides evenly into `86_400_000_000_000` seconds.
3450 ///
3451 /// # Example
3452 ///
3453 /// This example shows how to round a timestamp to the nearest 10 minute
3454 /// increment.
3455 ///
3456 /// ```
3457 /// use jiff::{RoundMode, Timestamp, TimestampRound, Unit};
3458 ///
3459 /// let ts: Timestamp = "2024-06-20 03:24:59Z".parse()?;
3460 /// assert_eq!(
3461 /// ts.round((Unit::Minute, 10))?.to_string(),
3462 /// "2024-06-20T03:20:00Z",
3463 /// );
3464 ///
3465 /// # Ok::<(), Box<dyn std::error::Error>>(())
3466 /// ```
3467 #[inline]
3468 pub fn increment(self, increment: i64) -> TimestampRound {
3469 TimestampRound { increment, ..self }
3470 }
3471
3472 /// Does the actual rounding.
3473 pub(crate) fn round(
3474 &self,
3475 timestamp: Timestamp,
3476 ) -> Result<Timestamp, Error> {
3477 let increment =
3478 Increment::for_timestamp(self.smallest, self.increment)?;
3479 Timestamp::from_duration(
3480 increment.round(self.mode, timestamp.as_duration())?,
3481 )
3482 }
3483}
3484
3485impl Default for TimestampRound {
3486 #[inline]
3487 fn default() -> TimestampRound {
3488 TimestampRound::new()
3489 }
3490}
3491
3492impl From<Unit> for TimestampRound {
3493 #[inline]
3494 fn from(unit: Unit) -> TimestampRound {
3495 TimestampRound::default().smallest(unit)
3496 }
3497}
3498
3499impl From<(Unit, i64)> for TimestampRound {
3500 #[inline]
3501 fn from((unit, increment): (Unit, i64)) -> TimestampRound {
3502 TimestampRound::from(unit).increment(increment)
3503 }
3504}
3505
3506#[cfg(test)]
3507mod tests {
3508 use alloc::string::ToString;
3509
3510 use std::io::Cursor;
3511
3512 use crate::{
3513 ToSpan,
3514 civil::{self, datetime},
3515 tz::Offset,
3516 util::b,
3517 };
3518
3519 use super::*;
3520
3521 fn mktime(seconds: i64, nanos: i32) -> Timestamp {
3522 Timestamp::new(seconds, nanos).unwrap()
3523 }
3524
3525 fn mkdt(
3526 year: i16,
3527 month: i8,
3528 day: i8,
3529 hour: i8,
3530 minute: i8,
3531 second: i8,
3532 nano: i32,
3533 ) -> civil::DateTime {
3534 let date = civil::Date::new(year, month, day).unwrap();
3535 let time = civil::Time::new(hour, minute, second, nano).unwrap();
3536 civil::DateTime::from_parts(date, time)
3537 }
3538
3539 #[cfg(feature = "std")]
3540 #[test]
3541 fn system_time_roundtrip() {
3542 use std::time::{Duration, SystemTime};
3543
3544 let epoch = SystemTime::UNIX_EPOCH;
3545 let duration = Duration::new(1_234_567_890, 123_456_789);
3546 let times = [
3547 Some(epoch),
3548 epoch.checked_add(Duration::from_nanos(1)),
3549 epoch.checked_sub(Duration::from_nanos(1)),
3550 epoch.checked_add(duration),
3551 epoch.checked_sub(duration),
3552 ];
3553 for system_time in times.into_iter().flatten() {
3554 let timestamp = Timestamp::try_from(system_time).unwrap();
3555 let zoned = timestamp.to_zoned_datetime(TimeZone::UTC);
3556 let results: [Result<SystemTime, Error>; 3] =
3557 [timestamp.try_into(), (&zoned).try_into(), zoned.try_into()];
3558 for result in results {
3559 assert_eq!(result.unwrap(), system_time);
3560 }
3561 }
3562 }
3563
3564 #[cfg(feature = "std")]
3565 #[test]
3566 fn system_time_limits() {
3567 use std::time::{Duration, SystemTime};
3568
3569 let epoch = SystemTime::UNIX_EPOCH;
3570 let times = [
3571 (
3572 Timestamp::MIN,
3573 epoch.checked_sub(Duration::from_secs(
3574 Timestamp::MIN.as_second().unsigned_abs(),
3575 )),
3576 ),
3577 (
3578 Timestamp::MAX,
3579 epoch.checked_add(Duration::new(
3580 Timestamp::MAX.as_second().unsigned_abs(),
3581 Timestamp::MAX.subsec_nanosecond().unsigned_abs(),
3582 )),
3583 ),
3584 ];
3585 // SystemTime's range varies by platform. In particular, some
3586 // platforms cannot represent Timestamp::MIN (see issue #467).
3587 for (timestamp, expected) in times {
3588 let zoned = timestamp.to_zoned_datetime(TimeZone::UTC);
3589 let results: [Result<SystemTime, Error>; 3] =
3590 [timestamp.try_into(), (&zoned).try_into(), zoned.try_into()];
3591 for result in results {
3592 assert_eq!(result.ok(), expected, "{timestamp}");
3593 }
3594 }
3595 }
3596
3597 #[test]
3598 fn to_datetime_specific_examples() {
3599 let tests = [
3600 ((b::UnixEpochSeconds::MIN, 0), (-9999, 1, 2, 1, 59, 59, 0)),
3601 (
3602 (b::UnixEpochSeconds::MIN + 1, -999_999_999),
3603 (-9999, 1, 2, 1, 59, 59, 1),
3604 ),
3605 ((-1, 1), (1969, 12, 31, 23, 59, 59, 1)),
3606 ((b::UnixEpochSeconds::MAX, 0), (9999, 12, 30, 22, 0, 0, 0)),
3607 ((b::UnixEpochSeconds::MAX - 1, 0), (9999, 12, 30, 21, 59, 59, 0)),
3608 (
3609 (b::UnixEpochSeconds::MAX - 1, 999_999_999),
3610 (9999, 12, 30, 21, 59, 59, 999_999_999),
3611 ),
3612 (
3613 (b::UnixEpochSeconds::MAX, 999_999_999),
3614 (9999, 12, 30, 22, 0, 0, 999_999_999),
3615 ),
3616 ((-2, -1), (1969, 12, 31, 23, 59, 57, 999_999_999)),
3617 ((-86398, -1), (1969, 12, 31, 0, 0, 1, 999_999_999)),
3618 ((-86399, -1), (1969, 12, 31, 0, 0, 0, 999_999_999)),
3619 ((-86400, -1), (1969, 12, 30, 23, 59, 59, 999_999_999)),
3620 ];
3621 for (t, dt) in tests {
3622 let timestamp = mktime(t.0, t.1);
3623 let datetime = mkdt(dt.0, dt.1, dt.2, dt.3, dt.4, dt.5, dt.6);
3624 assert_eq!(
3625 Offset::UTC.to_datetime(timestamp),
3626 datetime,
3627 "timestamp: {t:?}"
3628 );
3629 assert_eq!(
3630 timestamp,
3631 datetime.to_zoned_datetime(TimeZone::UTC).unwrap().timestamp(),
3632 "datetime: {datetime:?}"
3633 );
3634 }
3635 }
3636
3637 #[test]
3638 fn to_datetime_many_seconds_in_some_days() {
3639 let days = [
3640 i64::from(b::UnixEpochDays::MIN),
3641 -1000,
3642 -5,
3643 23,
3644 2000,
3645 i64::from(b::UnixEpochDays::MAX),
3646 ];
3647 let seconds = [
3648 -86_400, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4,
3649 5, 6, 7, 8, 9, 10, 86_400,
3650 ];
3651 let nanos = [0, 1, 5, 999_999_999];
3652 for day in days {
3653 let midpoint = day * 86_400;
3654 for second in seconds {
3655 let second = midpoint + second;
3656 if b::UnixEpochSeconds::check(second).is_err() {
3657 continue;
3658 }
3659 for nano in nanos {
3660 if second == b::UnixEpochSeconds::MIN && nano != 0 {
3661 continue;
3662 }
3663 let t = Timestamp::new(second, nano).unwrap();
3664 let Ok(got) = Offset::UTC
3665 .to_datetime(t)
3666 .to_zoned_datetime(TimeZone::UTC)
3667 else {
3668 continue;
3669 };
3670 assert_eq!(t, got.timestamp());
3671 }
3672 }
3673 }
3674 }
3675
3676 #[test]
3677 fn invalid_time() {
3678 assert!(Timestamp::new(b::UnixEpochSeconds::MIN, -1).is_err());
3679 assert!(
3680 Timestamp::new(b::UnixEpochSeconds::MIN, -999_999_999).is_err()
3681 );
3682 // These are greater than the minimum and thus okay!
3683 assert!(Timestamp::new(b::UnixEpochSeconds::MIN, 1).is_ok());
3684 assert!(Timestamp::new(b::UnixEpochSeconds::MIN, 999_999_999).is_ok());
3685 }
3686
3687 #[test]
3688 fn parse_timestamp_boundaries() {
3689 assert!("-009999-01-02T01:59:58.5Z".parse::<Timestamp>().is_err());
3690
3691 let tests = [
3692 ("-009999-01-02T01:59:58+00:00", None),
3693 ("-009999-01-02T01:59:58.000000001+00:00", None),
3694 ("-009999-01-02T01:59:58.5+00:00", None),
3695 ("-009999-01-02T01:59:58.999999999+00:00", None),
3696 ("-009999-01-02T01:59:59+00:00", Some(Timestamp::MIN)),
3697 (
3698 "-009999-01-02T01:59:59.000000001+00:00",
3699 Some(mktime(b::UnixEpochSeconds::MIN, 1)),
3700 ),
3701 ("-009999-01-02T03:59:58.5+02:00", None),
3702 ("-009999-01-01T23:59:58.5-02:00", None),
3703 ("-009999-01-02T03:59:59+02:00", Some(Timestamp::MIN)),
3704 ("-009999-01-01T23:59:59-02:00", Some(Timestamp::MIN)),
3705 ("9999-12-30T22:00:00.999999999+00:00", Some(Timestamp::MAX)),
3706 ("9999-12-30T22:00:01+00:00", None),
3707 ("9999-12-30T22:00:01.000000001+00:00", None),
3708 ];
3709 for (input, expected) in tests {
3710 assert_eq!(input.parse::<Timestamp>().ok(), expected, "{input}");
3711 assert_eq!(
3712 Timestamp::strptime("%6Y-%m-%dT%T%.f%:z", input).ok(),
3713 expected,
3714 "{input}",
3715 );
3716 }
3717 }
3718
3719 #[cfg(target_pointer_width = "64")]
3720 #[test]
3721 fn timestamp_size() {
3722 #[cfg(debug_assertions)]
3723 {
3724 assert_eq!(16, core::mem::size_of::<Timestamp>());
3725 }
3726 #[cfg(not(debug_assertions))]
3727 {
3728 assert_eq!(16, core::mem::size_of::<Timestamp>());
3729 }
3730 }
3731
3732 #[test]
3733 fn millisecond_roundtrip_boundaries() {
3734 let min = Timestamp::MIN.as_millisecond();
3735 let max = Timestamp::MAX.as_millisecond();
3736 for millisecond in [min, min + 1, max - 1, max] {
3737 let ts = Timestamp::from_millisecond(millisecond).unwrap();
3738 assert_eq!(ts.as_millisecond(), millisecond);
3739 assert_eq!(
3740 ts.as_nanosecond(),
3741 i128::from(millisecond) * 1_000_000
3742 );
3743 }
3744 for millisecond in [i64::MIN, min - 1, max + 1, i64::MAX] {
3745 assert!(Timestamp::from_millisecond(millisecond).is_err());
3746 }
3747 }
3748
3749 #[test]
3750 fn microsecond_roundtrip_boundaries() {
3751 let min = Timestamp::MIN.as_microsecond();
3752 let max = Timestamp::MAX.as_microsecond();
3753 for microsecond in [min, min + 1, max - 1, max] {
3754 let ts = Timestamp::from_microsecond(microsecond).unwrap();
3755 assert_eq!(ts.as_microsecond(), microsecond);
3756 assert_eq!(ts.as_nanosecond(), i128::from(microsecond) * 1_000);
3757 }
3758 for microsecond in [i64::MIN, min - 1, max + 1, i64::MAX] {
3759 assert!(Timestamp::from_microsecond(microsecond).is_err());
3760 }
3761 }
3762
3763 #[test]
3764 fn nanosecond_roundtrip_boundaries() {
3765 let inst = Timestamp::MIN;
3766 let nanos = inst.as_nanosecond();
3767 assert_eq!(0, nanos % (jcore::constants::NANOS_PER_SEC as i128));
3768 let got = Timestamp::from_nanosecond(nanos).unwrap();
3769 assert_eq!(inst, got);
3770
3771 let inst = Timestamp::MAX;
3772 let nanos = inst.as_nanosecond();
3773 assert_eq!(
3774 b::SignedSubsecNanosecond::MAX as i128,
3775 nanos % (jcore::constants::NANOS_PER_SEC as i128)
3776 );
3777 let got = Timestamp::from_nanosecond(nanos).unwrap();
3778 assert_eq!(inst, got);
3779
3780 #[cfg(feature = "alloc")]
3781 insta::assert_snapshot!(
3782 Timestamp::from_nanosecond(i128::MAX).unwrap_err(),
3783 @"parameter 'Unix timestamp nanoseconds' is not in the required range of -377705023201000000000..=253402207200999999999",
3784 );
3785 }
3786
3787 #[test]
3788 fn timestamp_saturating_add() {
3789 insta::assert_snapshot!(
3790 Timestamp::MIN.saturating_add(Span::new().days(1)).unwrap_err(),
3791 @"operation can only be performed with units of hours or smaller, but found non-zero 'day' units (operations on `jiff::Timestamp`, `jiff::tz::Offset` and `jiff::civil::Time` don't support calendar units in a `jiff::Span`)",
3792 )
3793 }
3794
3795 #[test]
3796 fn timestamp_saturating_sub() {
3797 insta::assert_snapshot!(
3798 Timestamp::MAX.saturating_sub(Span::new().days(1)).unwrap_err(),
3799 @"operation can only be performed with units of hours or smaller, but found non-zero 'day' units (operations on `jiff::Timestamp`, `jiff::tz::Offset` and `jiff::civil::Time` don't support calendar units in a `jiff::Span`)",
3800 )
3801 }
3802
3803 quickcheck::quickcheck! {
3804 fn prop_unix_seconds_roundtrip(t: Timestamp) -> quickcheck::TestResult {
3805 let dt = t.to_zoned_datetime(TimeZone::UTC).datetime();
3806 let Ok(got) = dt.to_zoned_datetime(TimeZone::UTC) else {
3807 return quickcheck::TestResult::discard();
3808 };
3809 quickcheck::TestResult::from_bool(t == got.timestamp())
3810 }
3811
3812 fn prop_nanos_roundtrip_unix(t: Timestamp) -> bool {
3813 let nanos = t.as_nanosecond();
3814 let got = Timestamp::from_nanosecond(nanos).unwrap();
3815 t == got
3816 }
3817
3818 fn timestamp_constant_and_new_are_same1(t: Timestamp) -> bool {
3819 let got = Timestamp::constant(t.as_second(), t.subsec_nanosecond());
3820 t == got
3821 }
3822
3823 fn timestamp_constant_and_new_are_same2(
3824 secs: i64,
3825 nanos: i32
3826 ) -> quickcheck::TestResult {
3827 let Ok(ts) = Timestamp::new(secs, nanos) else {
3828 return quickcheck::TestResult::discard();
3829 };
3830 let got = Timestamp::constant(secs, nanos);
3831 quickcheck::TestResult::from_bool(ts == got)
3832 }
3833 }
3834
3835 /// A `serde` deserializer compatibility test.
3836 ///
3837 /// Serde YAML used to be unable to deserialize `jiff` types,
3838 /// as deserializing from bytes is not supported by the deserializer.
3839 ///
3840 /// - <https://github.com/BurntSushi/jiff/issues/138>
3841 /// - <https://github.com/BurntSushi/jiff/discussions/148>
3842 #[test]
3843 fn timestamp_deserialize_yaml() {
3844 let expected = datetime(2024, 10, 31, 16, 33, 53, 123456789)
3845 .to_zoned_datetime(TimeZone::UTC)
3846 .unwrap()
3847 .timestamp();
3848
3849 let deserialized: Timestamp =
3850 serde_yaml::from_str("2024-10-31T16:33:53.123456789+00:00")
3851 .unwrap();
3852
3853 assert_eq!(deserialized, expected);
3854
3855 let deserialized: Timestamp = serde_yaml::from_slice(
3856 "2024-10-31T16:33:53.123456789+00:00".as_bytes(),
3857 )
3858 .unwrap();
3859
3860 assert_eq!(deserialized, expected);
3861
3862 let cursor = Cursor::new(b"2024-10-31T16:33:53.123456789+00:00");
3863 let deserialized: Timestamp = serde_yaml::from_reader(cursor).unwrap();
3864
3865 assert_eq!(deserialized, expected);
3866 }
3867
3868 #[test]
3869 fn timestamp_precision_loss() {
3870 let ts1: Timestamp =
3871 "2025-01-25T19:32:21.783444592+01:00".parse().unwrap();
3872 let span = 1.second();
3873 let ts2 = ts1 + span;
3874 assert_eq!(ts2.to_string(), "2025-01-25T18:32:22.783444592Z");
3875 assert_eq!(ts1, ts2 - span, "should be reversible");
3876 }
3877}