jiff/civil/datetime.rs
1use core::time::Duration as UnsignedDuration;
2
3use jcore::{bounds::Sign, civil::DateTime as JDateTime, constants as c};
4
5use crate::{
6 RoundMode, SignedDuration, Span, SpanRound, Unit,
7 civil::{
8 Date, DateWith, Era, ISOWeekDate, Time, TimeWith, Weekday, datetime,
9 },
10 duration::{Duration, SDuration},
11 error::{Error, ErrorContext, civil::Error as E},
12 fmt::{
13 self,
14 temporal::{self, DEFAULT_DATETIME_PARSER},
15 },
16 tz::TimeZone,
17 util::round::Increment,
18 zoned::ZonedDateTime,
19};
20
21/// A representation of a civil datetime in the Gregorian calendar.
22///
23/// A `DateTime` value corresponds to a pair of a [`Date`] and a [`Time`].
24/// That is, a datetime contains a year, month, day, hour, minute, second and
25/// the fractional number of nanoseconds.
26///
27/// A `DateTime` value is guaranteed to contain a valid date and time. For
28/// example, neither `2023-02-29T00:00:00` nor `2015-06-30T23:59:60` are
29/// valid `DateTime` values.
30///
31/// # Civil datetimes
32///
33/// A `DateTime` value behaves without regard to daylight saving time or time
34/// zones in general. When doing arithmetic on datetimes with spans defined in
35/// units of time (such as with [`DateTime::checked_add`]), days are considered
36/// to always be precisely `86,400` seconds long.
37///
38/// # Parsing and printing
39///
40/// The `DateTime` type provides convenient trait implementations of
41/// [`std::str::FromStr`] and [`std::fmt::Display`]:
42///
43/// ```
44/// use jiff::civil::DateTime;
45///
46/// let dt: DateTime = "2024-06-19 15:22:45".parse()?;
47/// assert_eq!(dt.to_string(), "2024-06-19T15:22:45");
48///
49/// # Ok::<(), Box<dyn std::error::Error>>(())
50/// ```
51///
52/// A civil `DateTime` can also be parsed from something that _contains_ a
53/// datetime, but with perhaps other data (such as an offset or time zone):
54///
55/// ```
56/// use jiff::civil::DateTime;
57///
58/// let dt: DateTime = "2024-06-19T15:22:45-04[America/New_York]".parse()?;
59/// assert_eq!(dt.to_string(), "2024-06-19T15:22:45");
60///
61/// # Ok::<(), Box<dyn std::error::Error>>(())
62/// ```
63///
64/// For more information on the specific format supported, see the
65/// [`fmt::temporal`](crate::fmt::temporal) module documentation.
66///
67/// # Default value
68///
69/// For convenience, this type implements the `Default` trait. Its default
70/// value corresponds to `0000-01-01T00:00:00.000000000`. That is, it is
71/// the datetime corresponding to `DateTime::from_parts(Date::default(),
72/// Time::default())`. One can also access this value via the `DateTime::ZERO`
73/// constant.
74///
75/// # Leap seconds
76///
77/// Jiff does not support leap seconds. Jiff behaves as if they don't exist.
78/// The only exception is that if one parses a datetime with a second component
79/// of `60`, then it is automatically constrained to `59`:
80///
81/// ```
82/// use jiff::civil::{DateTime, date};
83///
84/// let dt: DateTime = "2016-12-31 23:59:60".parse()?;
85/// assert_eq!(dt, date(2016, 12, 31).at(23, 59, 59, 0));
86///
87/// # Ok::<(), Box<dyn std::error::Error>>(())
88/// ```
89///
90/// # Comparisons
91///
92/// The `DateTime` type provides both `Eq` and `Ord` trait implementations to
93/// facilitate easy comparisons. When a datetime `dt1` occurs before a datetime
94/// `dt2`, then `dt1 < dt2`. For example:
95///
96/// ```
97/// use jiff::civil::date;
98///
99/// let dt1 = date(2024, 3, 11).at(1, 25, 15, 0);
100/// let dt2 = date(2025, 1, 31).at(0, 30, 0, 0);
101/// assert!(dt1 < dt2);
102/// ```
103///
104/// # Arithmetic
105///
106/// This type provides routines for adding and subtracting spans of time, as
107/// well as computing the span of time between two `DateTime` values.
108///
109/// For adding or subtracting spans of time, one can use any of the following
110/// routines:
111///
112/// * [`DateTime::checked_add`] or [`DateTime::checked_sub`] for checked
113/// arithmetic.
114/// * [`DateTime::saturating_add`] or [`DateTime::saturating_sub`] for
115/// saturating arithmetic.
116///
117/// Additionally, checked arithmetic is available via the `Add` and `Sub`
118/// trait implementations. When the result overflows, a panic occurs.
119///
120/// ```
121/// use jiff::{civil::date, ToSpan};
122///
123/// let start = date(2024, 2, 25).at(15, 45, 0, 0);
124/// let one_week_later = start + 1.weeks();
125/// assert_eq!(one_week_later, date(2024, 3, 3).at(15, 45, 0, 0));
126/// ```
127///
128/// One can compute the span of time between two datetimes using either
129/// [`DateTime::until`] or [`DateTime::since`]. It's also possible to subtract
130/// two `DateTime` values directly via a `Sub` trait implementation:
131///
132/// ```
133/// use jiff::{civil::date, ToSpan};
134///
135/// let datetime1 = date(2024, 5, 3).at(23, 30, 0, 0);
136/// let datetime2 = date(2024, 2, 25).at(7, 0, 0, 0);
137/// assert_eq!(
138/// datetime1 - datetime2,
139/// 68.days().hours(16).minutes(30).fieldwise(),
140/// );
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 days
145/// (as exemplified above), but we can ask for bigger units:
146///
147/// ```
148/// use jiff::{civil::date, ToSpan, Unit};
149///
150/// let datetime1 = date(2024, 5, 3).at(23, 30, 0, 0);
151/// let datetime2 = date(2024, 2, 25).at(7, 0, 0, 0);
152/// assert_eq!(
153/// datetime1.since((Unit::Year, datetime2))?,
154/// 2.months().days(7).hours(16).minutes(30).fieldwise(),
155/// );
156///
157/// # Ok::<(), Box<dyn std::error::Error>>(())
158/// ```
159///
160/// Or even round the span returned:
161///
162/// ```
163/// use jiff::{civil::{DateTimeDifference, date}, RoundMode, ToSpan, Unit};
164///
165/// let datetime1 = date(2024, 5, 3).at(23, 30, 0, 0);
166/// let datetime2 = date(2024, 2, 25).at(7, 0, 0, 0);
167/// assert_eq!(
168/// datetime1.since(
169/// DateTimeDifference::new(datetime2)
170/// .smallest(Unit::Day)
171/// .largest(Unit::Year),
172/// )?,
173/// 2.months().days(7).fieldwise(),
174/// );
175/// // `DateTimeDifference` uses truncation as a rounding mode by default,
176/// // but you can set the rounding mode to break ties away from zero:
177/// assert_eq!(
178/// datetime1.since(
179/// DateTimeDifference::new(datetime2)
180/// .smallest(Unit::Day)
181/// .largest(Unit::Year)
182/// .mode(RoundMode::HalfExpand),
183/// )?,
184/// // Rounds up to 8 days.
185/// 2.months().days(8).fieldwise(),
186/// );
187///
188/// # Ok::<(), Box<dyn std::error::Error>>(())
189/// ```
190///
191/// # Rounding
192///
193/// A `DateTime` can be rounded based on a [`DateTimeRound`] configuration of
194/// smallest units, rounding increment and rounding mode. Here's an example
195/// showing how to round to the nearest third hour:
196///
197/// ```
198/// use jiff::{civil::{DateTimeRound, date}, Unit};
199///
200/// let dt = date(2024, 6, 19).at(16, 27, 29, 999_999_999);
201/// assert_eq!(
202/// dt.round(DateTimeRound::new().smallest(Unit::Hour).increment(3))?,
203/// date(2024, 6, 19).at(15, 0, 0, 0),
204/// );
205/// // Or alternatively, make use of the `From<(Unit, i64)> for DateTimeRound`
206/// // trait implementation:
207/// assert_eq!(
208/// dt.round((Unit::Hour, 3))?,
209/// date(2024, 6, 19).at(15, 0, 0, 0),
210/// );
211///
212/// # Ok::<(), Box<dyn std::error::Error>>(())
213/// ```
214///
215/// See [`DateTime::round`] for more details.
216#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
217#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
218pub struct DateTime {
219 date: Date,
220 time: Time,
221}
222
223impl DateTime {
224 /// The minimum representable Gregorian datetime.
225 ///
226 /// The minimum is chosen such that any [`Timestamp`](crate::Timestamp)
227 /// combined with any valid time zone offset can be infallibly converted to
228 /// this type.
229 pub const MIN: DateTime = datetime(-9999, 1, 1, 0, 0, 0, 0);
230
231 /// The maximum representable Gregorian datetime.
232 ///
233 /// The maximum is chosen such that any [`Timestamp`](crate::Timestamp)
234 /// combined with any valid time zone offset can be infallibly converted to
235 /// this type.
236 pub const MAX: DateTime = datetime(9999, 12, 31, 23, 59, 59, 999_999_999);
237
238 /// The first day of the zeroth year.
239 ///
240 /// This is guaranteed to be equivalent to `DateTime::default()`.
241 ///
242 /// # Example
243 ///
244 /// ```
245 /// use jiff::civil::DateTime;
246 ///
247 /// assert_eq!(DateTime::ZERO, DateTime::default());
248 /// ```
249 pub const ZERO: DateTime = DateTime::from_parts(Date::ZERO, Time::MIN);
250
251 /// Creates a new `DateTime` value from its component year, month, day,
252 /// hour, minute, second and fractional subsecond (up to nanosecond
253 /// precision) values.
254 ///
255 /// To create a new datetime from another with a particular component, use
256 /// the methods on [`DateTimeWith`] via [`DateTime::with`].
257 ///
258 /// # Errors
259 ///
260 /// This returns an error when the given components do not correspond to a
261 /// valid datetime. Namely, all of the following must be true:
262 ///
263 /// * The year must be in the range `-9999..=9999`.
264 /// * The month must be in the range `1..=12`.
265 /// * The day must be at least `1` and must be at most the number of days
266 /// in the corresponding month. So for example, `2024-02-29` is valid but
267 /// `2023-02-29` is not.
268 /// * `0 <= hour <= 23`
269 /// * `0 <= minute <= 59`
270 /// * `0 <= second <= 59`
271 /// * `0 <= subsec_nanosecond <= 999,999,999`
272 ///
273 /// # Example
274 ///
275 /// This shows an example of a valid datetime:
276 ///
277 /// ```
278 /// use jiff::civil::DateTime;
279 ///
280 /// let d = DateTime::new(2024, 2, 29, 21, 30, 5, 123_456_789).unwrap();
281 /// assert_eq!(d.year(), 2024);
282 /// assert_eq!(d.month(), 2);
283 /// assert_eq!(d.day(), 29);
284 /// assert_eq!(d.hour(), 21);
285 /// assert_eq!(d.minute(), 30);
286 /// assert_eq!(d.second(), 5);
287 /// assert_eq!(d.millisecond(), 123);
288 /// assert_eq!(d.microsecond(), 456);
289 /// assert_eq!(d.nanosecond(), 789);
290 /// ```
291 ///
292 /// This shows some examples of invalid datetimes:
293 ///
294 /// ```
295 /// use jiff::civil::DateTime;
296 ///
297 /// assert!(DateTime::new(2023, 2, 29, 21, 30, 5, 0).is_err());
298 /// assert!(DateTime::new(2015, 6, 30, 23, 59, 60, 0).is_err());
299 /// assert!(DateTime::new(2024, 6, 20, 19, 58, 0, 1_000_000_000).is_err());
300 /// ```
301 #[inline]
302 pub fn new(
303 year: i16,
304 month: i8,
305 day: i8,
306 hour: i8,
307 minute: i8,
308 second: i8,
309 subsec_nanosecond: i32,
310 ) -> Result<DateTime, Error> {
311 let date = Date::new(year, month, day)?;
312 let time = Time::new(hour, minute, second, subsec_nanosecond)?;
313 Ok(DateTime { date, time })
314 }
315
316 /// Creates a new `DateTime` value in a `const` context.
317 ///
318 /// Note that an alternative syntax that is terser and perhaps easier to
319 /// read for the same operation is to combine
320 /// [`civil::date`](crate::civil::date()) with [`Date::at`].
321 ///
322 /// # Panics
323 ///
324 /// This routine panics when [`DateTime::new`] would return an error. That
325 /// is, when the given components do not correspond to a valid datetime.
326 /// Namely, all of the following must be true:
327 ///
328 /// * The year must be in the range `-9999..=9999`.
329 /// * The month must be in the range `1..=12`.
330 /// * The day must be at least `1` and must be at most the number of days
331 /// in the corresponding month. So for example, `2024-02-29` is valid but
332 /// `2023-02-29` is not.
333 /// * `0 <= hour <= 23`
334 /// * `0 <= minute <= 59`
335 /// * `0 <= second <= 59`
336 /// * `0 <= subsec_nanosecond <= 999,999,999`
337 ///
338 /// Similarly, when used in a const context, invalid parameters will
339 /// prevent your Rust program from compiling.
340 ///
341 /// # Example
342 ///
343 /// ```
344 /// use jiff::civil::DateTime;
345 ///
346 /// let dt = DateTime::constant(2024, 2, 29, 21, 30, 5, 123_456_789);
347 /// assert_eq!(dt.year(), 2024);
348 /// assert_eq!(dt.month(), 2);
349 /// assert_eq!(dt.day(), 29);
350 /// assert_eq!(dt.hour(), 21);
351 /// assert_eq!(dt.minute(), 30);
352 /// assert_eq!(dt.second(), 5);
353 /// assert_eq!(dt.millisecond(), 123);
354 /// assert_eq!(dt.microsecond(), 456);
355 /// assert_eq!(dt.nanosecond(), 789);
356 /// ```
357 ///
358 /// Or alternatively:
359 ///
360 /// ```
361 /// use jiff::civil::date;
362 ///
363 /// let dt = date(2024, 2, 29).at(21, 30, 5, 123_456_789);
364 /// assert_eq!(dt.year(), 2024);
365 /// assert_eq!(dt.month(), 2);
366 /// assert_eq!(dt.day(), 29);
367 /// assert_eq!(dt.hour(), 21);
368 /// assert_eq!(dt.minute(), 30);
369 /// assert_eq!(dt.second(), 5);
370 /// assert_eq!(dt.millisecond(), 123);
371 /// assert_eq!(dt.microsecond(), 456);
372 /// assert_eq!(dt.nanosecond(), 789);
373 /// ```
374 #[inline]
375 pub const fn constant(
376 year: i16,
377 month: i8,
378 day: i8,
379 hour: i8,
380 minute: i8,
381 second: i8,
382 subsec_nanosecond: i32,
383 ) -> DateTime {
384 let date = Date::constant(year, month, day);
385 let time = Time::constant(hour, minute, second, subsec_nanosecond);
386 DateTime { date, time }
387 }
388
389 /// Creates a `DateTime` from its constituent parts.
390 ///
391 /// Any combination of a valid `Date` and a valid `Time` results in a valid
392 /// `DateTime`.
393 ///
394 /// # Example
395 ///
396 /// This example shows how to build a datetime from its parts:
397 ///
398 /// ```
399 /// use jiff::civil::{DateTime, date, time};
400 ///
401 /// let dt = DateTime::from_parts(date(2024, 6, 6), time(6, 0, 0, 0));
402 /// assert_eq!(dt, date(2024, 6, 6).at(6, 0, 0, 0));
403 /// ```
404 #[inline]
405 pub const fn from_parts(date: Date, time: Time) -> DateTime {
406 DateTime { date, time }
407 }
408
409 /// Create a builder for constructing a new `DateTime` from the fields of
410 /// this datetime.
411 ///
412 /// See the methods on [`DateTimeWith`] for the different ways one can set
413 /// the fields of a new `DateTime`.
414 ///
415 /// # Example
416 ///
417 /// The builder ensures one can chain together the individual components of
418 /// a datetime without it failing at an intermediate step. For example, if
419 /// you had a date of `2024-10-31T00:00:00` and wanted to change both the
420 /// day and the month, and each setting was validated independent of the
421 /// other, you would need to be careful to set the day first and then the
422 /// month. In some cases, you would need to set the month first and then
423 /// the day!
424 ///
425 /// But with the builder, you can set values in any order:
426 ///
427 /// ```
428 /// use jiff::civil::date;
429 ///
430 /// let dt1 = date(2024, 10, 31).at(0, 0, 0, 0);
431 /// let dt2 = dt1.with().month(11).day(30).build()?;
432 /// assert_eq!(dt2, date(2024, 11, 30).at(0, 0, 0, 0));
433 ///
434 /// let dt1 = date(2024, 4, 30).at(0, 0, 0, 0);
435 /// let dt2 = dt1.with().day(31).month(7).build()?;
436 /// assert_eq!(dt2, date(2024, 7, 31).at(0, 0, 0, 0));
437 ///
438 /// # Ok::<(), Box<dyn std::error::Error>>(())
439 /// ```
440 #[inline]
441 pub fn with(self) -> DateTimeWith {
442 DateTimeWith::new(self)
443 }
444
445 /// Returns the year for this datetime.
446 ///
447 /// The value returned is guaranteed to be in the range `-9999..=9999`.
448 ///
449 /// # Example
450 ///
451 /// ```
452 /// use jiff::civil::date;
453 ///
454 /// let dt1 = date(2024, 3, 9).at(7, 30, 0, 0);
455 /// assert_eq!(dt1.year(), 2024);
456 ///
457 /// let dt2 = date(-2024, 3, 9).at(7, 30, 0, 0);
458 /// assert_eq!(dt2.year(), -2024);
459 ///
460 /// let dt3 = date(0, 3, 9).at(7, 30, 0, 0);
461 /// assert_eq!(dt3.year(), 0);
462 /// ```
463 #[inline]
464 pub fn year(self) -> i16 {
465 self.date().year()
466 }
467
468 /// Returns the year and its era.
469 ///
470 /// This crate specifically allows years to be negative or `0`, where as
471 /// years written for the Gregorian calendar are always positive and
472 /// greater than `0`. In the Gregorian calendar, the era labels `BCE` and
473 /// `CE` are used to disambiguate between years less than or equal to `0`
474 /// and years greater than `0`, respectively.
475 ///
476 /// The crate is designed this way so that years in the latest era (that
477 /// is, `CE`) are aligned with years in this crate.
478 ///
479 /// The year returned is guaranteed to be in the range `1..=10000`.
480 ///
481 /// # Example
482 ///
483 /// ```
484 /// use jiff::civil::{Era, date};
485 ///
486 /// let dt = date(2024, 10, 3).at(7, 30, 0, 0);
487 /// assert_eq!(dt.era_year(), (2024, Era::CE));
488 ///
489 /// let dt = date(1, 10, 3).at(7, 30, 0, 0);
490 /// assert_eq!(dt.era_year(), (1, Era::CE));
491 ///
492 /// let dt = date(0, 10, 3).at(7, 30, 0, 0);
493 /// assert_eq!(dt.era_year(), (1, Era::BCE));
494 ///
495 /// let dt = date(-1, 10, 3).at(7, 30, 0, 0);
496 /// assert_eq!(dt.era_year(), (2, Era::BCE));
497 ///
498 /// let dt = date(-10, 10, 3).at(7, 30, 0, 0);
499 /// assert_eq!(dt.era_year(), (11, Era::BCE));
500 ///
501 /// let dt = date(-9_999, 10, 3).at(7, 30, 0, 0);
502 /// assert_eq!(dt.era_year(), (10_000, Era::BCE));
503 /// ```
504 #[inline]
505 pub fn era_year(self) -> (i16, Era) {
506 self.date().era_year()
507 }
508
509 /// Returns the month for this datetime.
510 ///
511 /// The value returned is guaranteed to be in the range `1..=12`.
512 ///
513 /// # Example
514 ///
515 /// ```
516 /// use jiff::civil::date;
517 ///
518 /// let dt1 = date(2024, 3, 9).at(7, 30, 0, 0);
519 /// assert_eq!(dt1.month(), 3);
520 /// ```
521 #[inline]
522 pub fn month(self) -> i8 {
523 self.date().month()
524 }
525
526 /// Returns the day for this datetime.
527 ///
528 /// The value returned is guaranteed to be in the range `1..=31`.
529 ///
530 /// # Example
531 ///
532 /// ```
533 /// use jiff::civil::date;
534 ///
535 /// let dt1 = date(2024, 2, 29).at(7, 30, 0, 0);
536 /// assert_eq!(dt1.day(), 29);
537 /// ```
538 #[inline]
539 pub fn day(self) -> i8 {
540 self.date().day()
541 }
542
543 /// Returns the "hour" component of this datetime.
544 ///
545 /// The value returned is guaranteed to be in the range `0..=23`.
546 ///
547 /// # Example
548 ///
549 /// ```
550 /// use jiff::civil::date;
551 ///
552 /// let dt = date(2000, 1, 2).at(3, 4, 5, 123_456_789);
553 /// assert_eq!(dt.hour(), 3);
554 /// ```
555 #[inline]
556 pub fn hour(self) -> i8 {
557 self.time().hour()
558 }
559
560 /// Returns the "minute" component of this datetime.
561 ///
562 /// The value returned is guaranteed to be in the range `0..=59`.
563 ///
564 /// # Example
565 ///
566 /// ```
567 /// use jiff::civil::date;
568 ///
569 /// let dt = date(2000, 1, 2).at(3, 4, 5, 123_456_789);
570 /// assert_eq!(dt.minute(), 4);
571 /// ```
572 #[inline]
573 pub fn minute(self) -> i8 {
574 self.time().minute()
575 }
576
577 /// Returns the "second" component of this datetime.
578 ///
579 /// The value returned is guaranteed to be in the range `0..=59`.
580 ///
581 /// # Example
582 ///
583 /// ```
584 /// use jiff::civil::date;
585 ///
586 /// let dt = date(2000, 1, 2).at(3, 4, 5, 123_456_789);
587 /// assert_eq!(dt.second(), 5);
588 /// ```
589 #[inline]
590 pub fn second(self) -> i8 {
591 self.time().second()
592 }
593
594 /// Returns the "millisecond" component of this datetime.
595 ///
596 /// The value returned is guaranteed to be in the range `0..=999`.
597 ///
598 /// # Example
599 ///
600 /// ```
601 /// use jiff::civil::date;
602 ///
603 /// let dt = date(2000, 1, 2).at(3, 4, 5, 123_456_789);
604 /// assert_eq!(dt.millisecond(), 123);
605 /// ```
606 #[inline]
607 pub fn millisecond(self) -> i16 {
608 self.time().millisecond()
609 }
610
611 /// Returns the "microsecond" component of this datetime.
612 ///
613 /// The value returned is guaranteed to be in the range `0..=999`.
614 ///
615 /// # Example
616 ///
617 /// ```
618 /// use jiff::civil::date;
619 ///
620 /// let dt = date(2000, 1, 2).at(3, 4, 5, 123_456_789);
621 /// assert_eq!(dt.microsecond(), 456);
622 /// ```
623 #[inline]
624 pub fn microsecond(self) -> i16 {
625 self.time().microsecond()
626 }
627
628 /// Returns the "nanosecond" component of this datetime.
629 ///
630 /// The value returned is guaranteed to be in the range `0..=999`.
631 ///
632 /// # Example
633 ///
634 /// ```
635 /// use jiff::civil::date;
636 ///
637 /// let dt = date(2000, 1, 2).at(3, 4, 5, 123_456_789);
638 /// assert_eq!(dt.nanosecond(), 789);
639 /// ```
640 #[inline]
641 pub fn nanosecond(self) -> i16 {
642 self.time().nanosecond()
643 }
644
645 /// Returns the fractional nanosecond for this `DateTime` value.
646 ///
647 /// If you want to set this value on `DateTime`, then use
648 /// [`DateTimeWith::subsec_nanosecond`] via [`DateTime::with`].
649 ///
650 /// The value returned is guaranteed to be in the range `0..=999_999_999`.
651 ///
652 /// # Example
653 ///
654 /// This shows the relationship between constructing a `DateTime` value
655 /// with routines like `with().millisecond()` and accessing the entire
656 /// fractional part as a nanosecond:
657 ///
658 /// ```
659 /// use jiff::civil::date;
660 ///
661 /// let dt1 = date(2000, 1, 2).at(3, 4, 5, 123_456_789);
662 /// assert_eq!(dt1.subsec_nanosecond(), 123_456_789);
663 /// let dt2 = dt1.with().millisecond(333).build()?;
664 /// assert_eq!(dt2.subsec_nanosecond(), 333_456_789);
665 ///
666 /// # Ok::<(), Box<dyn std::error::Error>>(())
667 /// ```
668 ///
669 /// # Example: nanoseconds from a timestamp
670 ///
671 /// This shows how the fractional nanosecond part of a `DateTime` value
672 /// manifests from a specific timestamp.
673 ///
674 /// ```
675 /// use jiff::Timestamp;
676 ///
677 /// // 1,234 nanoseconds after the Unix epoch.
678 /// let zdt = Timestamp::new(0, 1_234)?.in_tz("UTC")?;
679 /// let dt = zdt.datetime();
680 /// assert_eq!(dt.subsec_nanosecond(), 1_234);
681 ///
682 /// // 1,234 nanoseconds before the Unix epoch.
683 /// let zdt = Timestamp::new(0, -1_234)?.in_tz("UTC")?;
684 /// let dt = zdt.datetime();
685 /// // The nanosecond is equal to `1_000_000_000 - 1_234`.
686 /// assert_eq!(dt.subsec_nanosecond(), 999998766);
687 /// // Looking at the other components of the time value might help.
688 /// assert_eq!(dt.hour(), 23);
689 /// assert_eq!(dt.minute(), 59);
690 /// assert_eq!(dt.second(), 59);
691 ///
692 /// # Ok::<(), Box<dyn std::error::Error>>(())
693 /// ```
694 #[inline]
695 pub fn subsec_nanosecond(self) -> i32 {
696 self.time().subsec_nanosecond()
697 }
698
699 /// Returns the weekday corresponding to this datetime.
700 ///
701 /// # Example
702 ///
703 /// ```
704 /// use jiff::civil::{Weekday, date};
705 ///
706 /// // The Unix epoch was on a Thursday.
707 /// let dt = date(1970, 1, 1).at(7, 30, 0, 0);
708 /// assert_eq!(dt.weekday(), Weekday::Thursday);
709 /// // One can also get the weekday as an offset in a variety of schemes.
710 /// assert_eq!(dt.weekday().to_monday_zero_offset(), 3);
711 /// assert_eq!(dt.weekday().to_monday_one_offset(), 4);
712 /// assert_eq!(dt.weekday().to_sunday_zero_offset(), 4);
713 /// assert_eq!(dt.weekday().to_sunday_one_offset(), 5);
714 /// ```
715 #[inline]
716 pub fn weekday(self) -> Weekday {
717 self.date().weekday()
718 }
719
720 /// Returns the ordinal day of the year that this datetime resides in.
721 ///
722 /// For leap years, this always returns a value in the range `1..=366`.
723 /// Otherwise, the value is in the range `1..=365`.
724 ///
725 /// # Example
726 ///
727 /// ```
728 /// use jiff::civil::date;
729 ///
730 /// let dt = date(2006, 8, 24).at(7, 30, 0, 0);
731 /// assert_eq!(dt.day_of_year(), 236);
732 ///
733 /// let dt = date(2023, 12, 31).at(7, 30, 0, 0);
734 /// assert_eq!(dt.day_of_year(), 365);
735 ///
736 /// let dt = date(2024, 12, 31).at(7, 30, 0, 0);
737 /// assert_eq!(dt.day_of_year(), 366);
738 /// ```
739 #[inline]
740 pub fn day_of_year(self) -> i16 {
741 self.date().day_of_year()
742 }
743
744 /// Returns the ordinal day of the year that this datetime resides in, but
745 /// ignores leap years.
746 ///
747 /// That is, the range of possible values returned by this routine is
748 /// `1..=365`, even if this date resides in a leap year. If this date is
749 /// February 29, then this routine returns `None`.
750 ///
751 /// The value `365` always corresponds to the last day in the year,
752 /// December 31, even for leap years.
753 ///
754 /// # Example
755 ///
756 /// ```
757 /// use jiff::civil::date;
758 ///
759 /// let dt = date(2006, 8, 24).at(7, 30, 0, 0);
760 /// assert_eq!(dt.day_of_year_no_leap(), Some(236));
761 ///
762 /// let dt = date(2023, 12, 31).at(7, 30, 0, 0);
763 /// assert_eq!(dt.day_of_year_no_leap(), Some(365));
764 ///
765 /// let dt = date(2024, 12, 31).at(7, 30, 0, 0);
766 /// assert_eq!(dt.day_of_year_no_leap(), Some(365));
767 ///
768 /// let dt = date(2024, 2, 29).at(7, 30, 0, 0);
769 /// assert_eq!(dt.day_of_year_no_leap(), None);
770 /// ```
771 #[inline]
772 pub fn day_of_year_no_leap(self) -> Option<i16> {
773 self.date().day_of_year_no_leap()
774 }
775
776 /// Returns the beginning of the day that this datetime resides in.
777 ///
778 /// That is, the datetime returned always keeps the same date, but its
779 /// time is always `00:00:00` (midnight).
780 ///
781 /// # Example
782 ///
783 /// ```
784 /// use jiff::civil::date;
785 ///
786 /// let dt = date(2024, 7, 3).at(7, 30, 10, 123_456_789);
787 /// assert_eq!(dt.start_of_day(), date(2024, 7, 3).at(0, 0, 0, 0));
788 /// ```
789 #[inline]
790 pub fn start_of_day(&self) -> DateTime {
791 DateTime::from_parts(self.date(), Time::MIN)
792 }
793
794 /// Returns the end of the day that this datetime resides in.
795 ///
796 /// That is, the datetime returned always keeps the same date, but its
797 /// time is always `23:59:59.999999999`.
798 ///
799 /// # Example
800 ///
801 /// ```
802 /// use jiff::civil::date;
803 ///
804 /// let dt = date(2024, 7, 3).at(7, 30, 10, 123_456_789);
805 /// assert_eq!(
806 /// dt.end_of_day(),
807 /// date(2024, 7, 3).at(23, 59, 59, 999_999_999),
808 /// );
809 /// ```
810 #[inline]
811 pub fn end_of_day(&self) -> DateTime {
812 DateTime::from_parts(self.date(), Time::MAX)
813 }
814
815 /// Returns the first date of the month that this datetime resides in.
816 ///
817 /// The time in the datetime returned remains unchanged.
818 ///
819 /// # Example
820 ///
821 /// ```
822 /// use jiff::civil::date;
823 ///
824 /// let dt = date(2024, 2, 29).at(7, 30, 0, 0);
825 /// assert_eq!(dt.first_of_month(), date(2024, 2, 1).at(7, 30, 0, 0));
826 /// ```
827 #[inline]
828 pub fn first_of_month(self) -> DateTime {
829 DateTime::from_parts(self.date().first_of_month(), self.time())
830 }
831
832 /// Returns the last date of the month that this datetime resides in.
833 ///
834 /// The time in the datetime returned remains unchanged.
835 ///
836 /// # Example
837 ///
838 /// ```
839 /// use jiff::civil::date;
840 ///
841 /// let dt = date(2024, 2, 5).at(7, 30, 0, 0);
842 /// assert_eq!(dt.last_of_month(), date(2024, 2, 29).at(7, 30, 0, 0));
843 /// ```
844 #[inline]
845 pub fn last_of_month(self) -> DateTime {
846 DateTime::from_parts(self.date().last_of_month(), self.time())
847 }
848
849 /// Returns the total number of days in the the month in which this
850 /// datetime resides.
851 ///
852 /// This is guaranteed to always return one of the following values,
853 /// depending on the year and the month: 28, 29, 30 or 31.
854 ///
855 /// # Example
856 ///
857 /// ```
858 /// use jiff::civil::date;
859 ///
860 /// let dt = date(2024, 2, 10).at(7, 30, 0, 0);
861 /// assert_eq!(dt.days_in_month(), 29);
862 ///
863 /// let dt = date(2023, 2, 10).at(7, 30, 0, 0);
864 /// assert_eq!(dt.days_in_month(), 28);
865 ///
866 /// let dt = date(2024, 8, 15).at(7, 30, 0, 0);
867 /// assert_eq!(dt.days_in_month(), 31);
868 /// ```
869 #[inline]
870 pub fn days_in_month(self) -> i8 {
871 self.date().days_in_month()
872 }
873
874 /// Returns the first date of the year that this datetime resides in.
875 ///
876 /// The time in the datetime returned remains unchanged.
877 ///
878 /// # Example
879 ///
880 /// ```
881 /// use jiff::civil::date;
882 ///
883 /// let dt = date(2024, 2, 29).at(7, 30, 0, 0);
884 /// assert_eq!(dt.first_of_year(), date(2024, 1, 1).at(7, 30, 0, 0));
885 /// ```
886 #[inline]
887 pub fn first_of_year(self) -> DateTime {
888 DateTime::from_parts(self.date().first_of_year(), self.time())
889 }
890
891 /// Returns the last date of the year that this datetime resides in.
892 ///
893 /// The time in the datetime returned remains unchanged.
894 ///
895 /// # Example
896 ///
897 /// ```
898 /// use jiff::civil::date;
899 ///
900 /// let dt = date(2024, 2, 5).at(7, 30, 0, 0);
901 /// assert_eq!(dt.last_of_year(), date(2024, 12, 31).at(7, 30, 0, 0));
902 /// ```
903 #[inline]
904 pub fn last_of_year(self) -> DateTime {
905 DateTime::from_parts(self.date().last_of_year(), self.time())
906 }
907
908 /// Returns the total number of days in the the year in which this datetime
909 /// resides.
910 ///
911 /// This is guaranteed to always return either `365` or `366`.
912 ///
913 /// # Example
914 ///
915 /// ```
916 /// use jiff::civil::date;
917 ///
918 /// let dt = date(2024, 7, 10).at(7, 30, 0, 0);
919 /// assert_eq!(dt.days_in_year(), 366);
920 ///
921 /// let dt = date(2023, 7, 10).at(7, 30, 0, 0);
922 /// assert_eq!(dt.days_in_year(), 365);
923 /// ```
924 #[inline]
925 pub fn days_in_year(self) -> i16 {
926 self.date().days_in_year()
927 }
928
929 /// Returns true if and only if the year in which this datetime resides is
930 /// a leap year.
931 ///
932 /// # Example
933 ///
934 /// ```
935 /// use jiff::civil::date;
936 ///
937 /// assert!(date(2024, 1, 1).at(7, 30, 0, 0).in_leap_year());
938 /// assert!(!date(2023, 12, 31).at(7, 30, 0, 0).in_leap_year());
939 /// ```
940 #[inline]
941 pub fn in_leap_year(self) -> bool {
942 self.date().in_leap_year()
943 }
944
945 /// Returns the datetime with a date immediately following this one.
946 ///
947 /// The time in the datetime returned remains unchanged.
948 ///
949 /// # Errors
950 ///
951 /// This returns an error when this datetime's date is the maximum value.
952 ///
953 /// # Example
954 ///
955 /// ```
956 /// use jiff::civil::{DateTime, date};
957 ///
958 /// let dt = date(2024, 2, 28).at(7, 30, 0, 0);
959 /// assert_eq!(dt.tomorrow()?, date(2024, 2, 29).at(7, 30, 0, 0));
960 ///
961 /// // The max doesn't have a tomorrow.
962 /// assert!(DateTime::MAX.tomorrow().is_err());
963 ///
964 /// # Ok::<(), Box<dyn std::error::Error>>(())
965 /// ```
966 #[inline]
967 pub fn tomorrow(self) -> Result<DateTime, Error> {
968 Ok(DateTime::from_parts(self.date().tomorrow()?, self.time()))
969 }
970
971 /// Returns the datetime with a date immediately preceding this one.
972 ///
973 /// The time in the datetime returned remains unchanged.
974 ///
975 /// # Errors
976 ///
977 /// This returns an error when this datetime's date is the minimum value.
978 ///
979 /// # Example
980 ///
981 /// ```
982 /// use jiff::civil::{DateTime, date};
983 ///
984 /// let dt = date(2024, 3, 1).at(7, 30, 0, 0);
985 /// assert_eq!(dt.yesterday()?, date(2024, 2, 29).at(7, 30, 0, 0));
986 ///
987 /// // The min doesn't have a yesterday.
988 /// assert!(DateTime::MIN.yesterday().is_err());
989 ///
990 /// # Ok::<(), Box<dyn std::error::Error>>(())
991 /// ```
992 #[inline]
993 pub fn yesterday(self) -> Result<DateTime, Error> {
994 Ok(DateTime::from_parts(self.date().yesterday()?, self.time()))
995 }
996
997 /// Returns the "nth" weekday from the beginning or end of the month in
998 /// which this datetime resides.
999 ///
1000 /// The `nth` parameter can be positive or negative. A positive value
1001 /// computes the "nth" weekday from the beginning of the month. A negative
1002 /// value computes the "nth" weekday from the end of the month. So for
1003 /// example, use `-1` to "find the last weekday" in this date's month.
1004 ///
1005 /// The time in the datetime returned remains unchanged.
1006 ///
1007 /// # Errors
1008 ///
1009 /// This returns an error when `nth` is `0`, or if it is `5` or `-5` and
1010 /// there is no 5th weekday from the beginning or end of the month.
1011 ///
1012 /// # Example
1013 ///
1014 /// This shows how to get the nth weekday in a month, starting from the
1015 /// beginning of the month:
1016 ///
1017 /// ```
1018 /// use jiff::civil::{Weekday, date};
1019 ///
1020 /// let dt = date(2017, 3, 1).at(7, 30, 0, 0);
1021 /// let second_friday = dt.nth_weekday_of_month(2, Weekday::Friday)?;
1022 /// assert_eq!(second_friday, date(2017, 3, 10).at(7, 30, 0, 0));
1023 ///
1024 /// # Ok::<(), Box<dyn std::error::Error>>(())
1025 /// ```
1026 ///
1027 /// This shows how to do the reverse of the above. That is, the nth _last_
1028 /// weekday in a month:
1029 ///
1030 /// ```
1031 /// use jiff::civil::{Weekday, date};
1032 ///
1033 /// let dt = date(2024, 3, 1).at(7, 30, 0, 0);
1034 /// let last_thursday = dt.nth_weekday_of_month(-1, Weekday::Thursday)?;
1035 /// assert_eq!(last_thursday, date(2024, 3, 28).at(7, 30, 0, 0));
1036 /// let second_last_thursday = dt.nth_weekday_of_month(
1037 /// -2,
1038 /// Weekday::Thursday,
1039 /// )?;
1040 /// assert_eq!(second_last_thursday, date(2024, 3, 21).at(7, 30, 0, 0));
1041 ///
1042 /// # Ok::<(), Box<dyn std::error::Error>>(())
1043 /// ```
1044 ///
1045 /// This routine can return an error if there isn't an `nth` weekday
1046 /// for this month. For example, March 2024 only has 4 Mondays:
1047 ///
1048 /// ```
1049 /// use jiff::civil::{Weekday, date};
1050 ///
1051 /// let dt = date(2024, 3, 25).at(7, 30, 0, 0);
1052 /// let fourth_monday = dt.nth_weekday_of_month(4, Weekday::Monday)?;
1053 /// assert_eq!(fourth_monday, date(2024, 3, 25).at(7, 30, 0, 0));
1054 /// // There is no 5th Monday.
1055 /// assert!(dt.nth_weekday_of_month(5, Weekday::Monday).is_err());
1056 /// // Same goes for counting backwards.
1057 /// assert!(dt.nth_weekday_of_month(-5, Weekday::Monday).is_err());
1058 ///
1059 /// # Ok::<(), Box<dyn std::error::Error>>(())
1060 /// ```
1061 #[inline]
1062 pub fn nth_weekday_of_month(
1063 self,
1064 nth: i8,
1065 weekday: Weekday,
1066 ) -> Result<DateTime, Error> {
1067 let date = self.date().nth_weekday_of_month(nth, weekday)?;
1068 Ok(DateTime::from_parts(date, self.time()))
1069 }
1070
1071 /// Returns the "nth" weekday from this datetime, not including itself.
1072 ///
1073 /// The `nth` parameter can be positive or negative. A positive value
1074 /// computes the "nth" weekday starting at the day after this date and
1075 /// going forwards in time. A negative value computes the "nth" weekday
1076 /// starting at the day before this date and going backwards in time.
1077 ///
1078 /// For example, if this datetime's weekday is a Sunday and the first
1079 /// Sunday is asked for (that is, `dt.nth_weekday(1, Weekday::Sunday)`),
1080 /// then the result is a week from this datetime corresponding to the
1081 /// following Sunday.
1082 ///
1083 /// The time in the datetime returned remains unchanged.
1084 ///
1085 /// # Errors
1086 ///
1087 /// This returns an error when `nth` is `0`, or if it would otherwise
1088 /// result in a date that overflows the minimum/maximum values of
1089 /// `DateTime`.
1090 ///
1091 /// # Example
1092 ///
1093 /// This example shows how to find the "nth" weekday going forwards in
1094 /// time:
1095 ///
1096 /// ```
1097 /// use jiff::civil::{Weekday, date};
1098 ///
1099 /// // Use a Sunday in March as our start date.
1100 /// let dt = date(2024, 3, 10).at(7, 30, 0, 0);
1101 /// assert_eq!(dt.weekday(), Weekday::Sunday);
1102 ///
1103 /// // The first next Monday is tomorrow!
1104 /// let next_monday = dt.nth_weekday(1, Weekday::Monday)?;
1105 /// assert_eq!(next_monday, date(2024, 3, 11).at(7, 30, 0, 0));
1106 ///
1107 /// // But the next Sunday is a week away, because this doesn't
1108 /// // include the current weekday.
1109 /// let next_sunday = dt.nth_weekday(1, Weekday::Sunday)?;
1110 /// assert_eq!(next_sunday, date(2024, 3, 17).at(7, 30, 0, 0));
1111 ///
1112 /// // "not this Thursday, but next Thursday"
1113 /// let next_next_thursday = dt.nth_weekday(2, Weekday::Thursday)?;
1114 /// assert_eq!(next_next_thursday, date(2024, 3, 21).at(7, 30, 0, 0));
1115 ///
1116 /// # Ok::<(), Box<dyn std::error::Error>>(())
1117 /// ```
1118 ///
1119 /// This example shows how to find the "nth" weekday going backwards in
1120 /// time:
1121 ///
1122 /// ```
1123 /// use jiff::civil::{Weekday, date};
1124 ///
1125 /// // Use a Sunday in March as our start date.
1126 /// let dt = date(2024, 3, 10).at(7, 30, 0, 0);
1127 /// assert_eq!(dt.weekday(), Weekday::Sunday);
1128 ///
1129 /// // "last Saturday" was yesterday!
1130 /// let last_saturday = dt.nth_weekday(-1, Weekday::Saturday)?;
1131 /// assert_eq!(last_saturday, date(2024, 3, 9).at(7, 30, 0, 0));
1132 ///
1133 /// // "last Sunday" was a week ago.
1134 /// let last_sunday = dt.nth_weekday(-1, Weekday::Sunday)?;
1135 /// assert_eq!(last_sunday, date(2024, 3, 3).at(7, 30, 0, 0));
1136 ///
1137 /// // "not last Thursday, but the one before"
1138 /// let prev_prev_thursday = dt.nth_weekday(-2, Weekday::Thursday)?;
1139 /// assert_eq!(prev_prev_thursday, date(2024, 2, 29).at(7, 30, 0, 0));
1140 ///
1141 /// # Ok::<(), Box<dyn std::error::Error>>(())
1142 /// ```
1143 ///
1144 /// This example shows that overflow results in an error in either
1145 /// direction:
1146 ///
1147 /// ```
1148 /// use jiff::civil::{DateTime, Weekday};
1149 ///
1150 /// let dt = DateTime::MAX;
1151 /// assert_eq!(dt.weekday(), Weekday::Friday);
1152 /// assert!(dt.nth_weekday(1, Weekday::Saturday).is_err());
1153 ///
1154 /// let dt = DateTime::MIN;
1155 /// assert_eq!(dt.weekday(), Weekday::Monday);
1156 /// assert!(dt.nth_weekday(-1, Weekday::Sunday).is_err());
1157 /// ```
1158 ///
1159 /// # Example: the start of Israeli summer time
1160 ///
1161 /// Israeli law says (at present, as of 2024-03-11) that DST or
1162 /// "summer time" starts on the Friday before the last Sunday in
1163 /// March. We can find that date using both `nth_weekday` and
1164 /// [`DateTime::nth_weekday_of_month`]:
1165 ///
1166 /// ```
1167 /// use jiff::civil::{Weekday, date};
1168 ///
1169 /// let march = date(2024, 3, 1).at(0, 0, 0, 0);
1170 /// let last_sunday = march.nth_weekday_of_month(-1, Weekday::Sunday)?;
1171 /// let dst_starts_on = last_sunday.nth_weekday(-1, Weekday::Friday)?;
1172 /// assert_eq!(dst_starts_on, date(2024, 3, 29).at(0, 0, 0, 0));
1173 ///
1174 /// # Ok::<(), Box<dyn std::error::Error>>(())
1175 /// ```
1176 ///
1177 /// # Example: getting the start of the week
1178 ///
1179 /// Given a date, one can use `nth_weekday` to determine the start of the
1180 /// week in which the date resides in. This might vary based on whether
1181 /// the weeks start on Sunday or Monday. This example shows how to handle
1182 /// both.
1183 ///
1184 /// ```
1185 /// use jiff::civil::{Weekday, date};
1186 ///
1187 /// let dt = date(2024, 3, 15).at(7, 30, 0, 0);
1188 /// // For weeks starting with Sunday.
1189 /// let start_of_week = dt.tomorrow()?.nth_weekday(-1, Weekday::Sunday)?;
1190 /// assert_eq!(start_of_week, date(2024, 3, 10).at(7, 30, 0, 0));
1191 /// // For weeks starting with Monday.
1192 /// let start_of_week = dt.tomorrow()?.nth_weekday(-1, Weekday::Monday)?;
1193 /// assert_eq!(start_of_week, date(2024, 3, 11).at(7, 30, 0, 0));
1194 ///
1195 /// # Ok::<(), Box<dyn std::error::Error>>(())
1196 /// ```
1197 ///
1198 /// In the above example, we first get the date after the current one
1199 /// because `nth_weekday` does not consider itself when counting. This
1200 /// works as expected even at the boundaries of a week:
1201 ///
1202 /// ```
1203 /// use jiff::civil::{Time, Weekday, date};
1204 ///
1205 /// // The start of the week.
1206 /// let dt = date(2024, 3, 10).at(0, 0, 0, 0);
1207 /// let start_of_week = dt.tomorrow()?.nth_weekday(-1, Weekday::Sunday)?;
1208 /// assert_eq!(start_of_week, date(2024, 3, 10).at(0, 0, 0, 0));
1209 /// // The end of the week.
1210 /// let dt = date(2024, 3, 16).at(23, 59, 59, 999_999_999);
1211 /// let start_of_week = dt
1212 /// .tomorrow()?
1213 /// .nth_weekday(-1, Weekday::Sunday)?
1214 /// .with().time(Time::midnight()).build()?;
1215 /// assert_eq!(start_of_week, date(2024, 3, 10).at(0, 0, 0, 0));
1216 ///
1217 /// # Ok::<(), Box<dyn std::error::Error>>(())
1218 /// ```
1219 #[inline]
1220 pub fn nth_weekday(
1221 self,
1222 nth: i32,
1223 weekday: Weekday,
1224 ) -> Result<DateTime, Error> {
1225 let date = self.date().nth_weekday(nth, weekday)?;
1226 Ok(DateTime::from_parts(date, self.time()))
1227 }
1228
1229 /// Returns the date component of this datetime.
1230 ///
1231 /// # Example
1232 ///
1233 /// ```
1234 /// use jiff::civil::date;
1235 ///
1236 /// let dt = date(2024, 3, 14).at(18, 45, 0, 0);
1237 /// assert_eq!(dt.date(), date(2024, 3, 14));
1238 /// ```
1239 #[inline]
1240 pub fn date(self) -> Date {
1241 self.date
1242 }
1243
1244 /// Returns the time component of this datetime.
1245 ///
1246 /// # Example
1247 ///
1248 /// ```
1249 /// use jiff::civil::{date, time};
1250 ///
1251 /// let dt = date(2024, 3, 14).at(18, 45, 0, 0);
1252 /// assert_eq!(dt.time(), time(18, 45, 0, 0));
1253 /// ```
1254 #[inline]
1255 pub fn time(self) -> Time {
1256 self.time
1257 }
1258
1259 /// Construct an [ISO 8601 week date] from this datetime.
1260 ///
1261 /// The [`ISOWeekDate`] type describes itself in more detail, but in
1262 /// brief, the ISO week date calendar system eschews months in favor of
1263 /// weeks.
1264 ///
1265 /// This routine is equivalent to
1266 /// [`ISOWeekDate::from_date(dt.date())`](ISOWeekDate::from_date).
1267 ///
1268 /// [ISO 8601 week date]: https://en.wikipedia.org/wiki/ISO_week_date
1269 ///
1270 /// # Example
1271 ///
1272 /// This shows a number of examples demonstrating the conversion from a
1273 /// Gregorian date to an ISO 8601 week date:
1274 ///
1275 /// ```
1276 /// use jiff::civil::{Date, Time, Weekday, date};
1277 ///
1278 /// let dt = date(1995, 1, 1).at(18, 45, 0, 0);
1279 /// let weekdate = dt.iso_week_date();
1280 /// assert_eq!(weekdate.year(), 1994);
1281 /// assert_eq!(weekdate.week(), 52);
1282 /// assert_eq!(weekdate.weekday(), Weekday::Sunday);
1283 ///
1284 /// let dt = date(1996, 12, 31).at(18, 45, 0, 0);
1285 /// let weekdate = dt.iso_week_date();
1286 /// assert_eq!(weekdate.year(), 1997);
1287 /// assert_eq!(weekdate.week(), 1);
1288 /// assert_eq!(weekdate.weekday(), Weekday::Tuesday);
1289 ///
1290 /// let dt = date(2019, 12, 30).at(18, 45, 0, 0);
1291 /// let weekdate = dt.iso_week_date();
1292 /// assert_eq!(weekdate.year(), 2020);
1293 /// assert_eq!(weekdate.week(), 1);
1294 /// assert_eq!(weekdate.weekday(), Weekday::Monday);
1295 ///
1296 /// let dt = date(2024, 3, 9).at(18, 45, 0, 0);
1297 /// let weekdate = dt.iso_week_date();
1298 /// assert_eq!(weekdate.year(), 2024);
1299 /// assert_eq!(weekdate.week(), 10);
1300 /// assert_eq!(weekdate.weekday(), Weekday::Saturday);
1301 ///
1302 /// let dt = Date::MIN.to_datetime(Time::MIN);
1303 /// let weekdate = dt.iso_week_date();
1304 /// assert_eq!(weekdate.year(), -9999);
1305 /// assert_eq!(weekdate.week(), 1);
1306 /// assert_eq!(weekdate.weekday(), Weekday::Monday);
1307 ///
1308 /// let dt = Date::MAX.to_datetime(Time::MAX);
1309 /// let weekdate = dt.iso_week_date();
1310 /// assert_eq!(weekdate.year(), 9999);
1311 /// assert_eq!(weekdate.week(), 52);
1312 /// assert_eq!(weekdate.weekday(), Weekday::Friday);
1313 /// ```
1314 #[inline]
1315 pub fn iso_week_date(self) -> ISOWeekDate {
1316 self.date().iso_week_date()
1317 }
1318
1319 /// Converts a civil datetime to a [`ZonedDateTime`] datetime by adding the
1320 /// given time zone.
1321 ///
1322 /// The name given is resolved to a [`TimeZone`] by using the default
1323 /// [`TimeZoneDatabase`](crate::tz::TimeZoneDatabase) created by
1324 /// [`tz::db`](crate::tz::db). Indeed, this is a convenience function for
1325 /// [`DateTime::to_zoned_datetime`] where the time zone database lookup is
1326 /// done automatically.
1327 ///
1328 /// In some cases, a civil datetime may be ambiguous in a
1329 /// particular time zone. This routine automatically utilizes the
1330 /// [`Disambiguation::Compatible`](crate::tz::Disambiguation) strategy
1331 /// for resolving ambiguities. That is, if a civil datetime occurs in a
1332 /// backward transition (called a fold), then the earlier time is selected.
1333 /// Or if a civil datetime occurs in a forward transition (called a gap),
1334 /// then the later time is selected.
1335 ///
1336 /// To convert a datetime to a `ZonedDateTime` using a different
1337 /// disambiguation strategy, use
1338 /// [`TimeZone::to_ambiguous_zoned_datetime`].
1339 ///
1340 /// # Errors
1341 ///
1342 /// This returns an error when the given time zone name could not be found
1343 /// in the default time zone database.
1344 ///
1345 /// This also returns an error if this datetime could not be represented as
1346 /// an instant. This can occur in some cases near the minimum and maximum
1347 /// boundaries of a `DateTime`.
1348 ///
1349 /// # Example
1350 ///
1351 /// This is a simple example of converting a civil datetime (a "wall" or
1352 /// "local" or "naive" datetime) to a datetime that is aware of its time
1353 /// zone:
1354 ///
1355 /// ```
1356 /// use jiff::civil::DateTime;
1357 ///
1358 /// let dt: DateTime = "2024-06-20 15:06".parse()?;
1359 /// let zdt = dt.in_tz("America/New_York")?;
1360 /// assert_eq!(zdt.to_string(), "2024-06-20T15:06:00-04:00[America/New_York]");
1361 ///
1362 /// # Ok::<(), Box<dyn std::error::Error>>(())
1363 /// ```
1364 ///
1365 /// # Example: dealing with ambiguity
1366 ///
1367 /// In the `America/New_York` time zone, there was a forward transition
1368 /// at `2024-03-10 02:00:00` civil time, and a backward transition at
1369 /// `2024-11-03 01:00:00` civil time. In the former case, a gap was
1370 /// created such that the 2 o'clock hour never appeared on clocks for folks
1371 /// in the `America/New_York` time zone. In the latter case, a fold was
1372 /// created such that the 1 o'clock hour was repeated. Thus, March 10, 2024
1373 /// in New York was 23 hours long, while November 3, 2024 in New York was
1374 /// 25 hours long.
1375 ///
1376 /// This example shows how datetimes in these gaps and folds are resolved
1377 /// by default:
1378 ///
1379 /// ```
1380 /// use jiff::civil::DateTime;
1381 ///
1382 /// // This is the gap, where by default we select the later time.
1383 /// let dt: DateTime = "2024-03-10 02:30".parse()?;
1384 /// let zdt = dt.in_tz("America/New_York")?;
1385 /// assert_eq!(zdt.to_string(), "2024-03-10T03:30:00-04:00[America/New_York]");
1386 ///
1387 /// // This is the fold, where by default we select the earlier time.
1388 /// let dt: DateTime = "2024-11-03 01:30".parse()?;
1389 /// let zdt = dt.in_tz("America/New_York")?;
1390 /// // Since this is a fold, the wall clock time is repeated. It might be
1391 /// // hard to see that this is the earlier time, but notice the offset:
1392 /// // it is the offset for DST time in New York. The later time, or the
1393 /// // repetition of the 1 o'clock hour, would occur in standard time,
1394 /// // which is an offset of -05 for New York.
1395 /// assert_eq!(zdt.to_string(), "2024-11-03T01:30:00-04:00[America/New_York]");
1396 ///
1397 /// # Ok::<(), Box<dyn std::error::Error>>(())
1398 /// ```
1399 ///
1400 /// # Example: errors
1401 ///
1402 /// This routine can return an error when the time zone is unrecognized:
1403 ///
1404 /// ```
1405 /// use jiff::civil::date;
1406 ///
1407 /// let dt = date(2024, 6, 20).at(15, 6, 0, 0);
1408 /// assert!(dt.in_tz("does not exist").is_err());
1409 /// ```
1410 ///
1411 /// Note that even if a time zone exists in, say, the IANA database, there
1412 /// may have been a problem reading it from your system's installation of
1413 /// that database. To see what wrong, enable Jiff's `logging` crate feature
1414 /// and install a logger. If there was a failure, then a `WARN` level log
1415 /// message should be emitted.
1416 ///
1417 /// This routine can also fail if this datetime cannot be represented
1418 /// within the allowable timestamp limits:
1419 ///
1420 /// ```
1421 /// use jiff::{civil::DateTime, tz::{Offset, TimeZone}};
1422 ///
1423 /// let dt = DateTime::MAX;
1424 /// // All errors because the combination of the offset and the datetime
1425 /// // isn't enough to fit into timestamp limits.
1426 /// assert!(dt.in_tz("UTC").is_err());
1427 /// assert!(dt.in_tz("America/New_York").is_err());
1428 /// assert!(dt.in_tz("Australia/Hobart").is_err());
1429 /// // In fact, the only valid offset one can use to turn the maximum civil
1430 /// // datetime into a ZonedDateTime value is the maximum offset:
1431 /// let tz = Offset::from_seconds(93_599).unwrap().to_time_zone();
1432 /// assert!(dt.to_zoned_datetime(tz).is_ok());
1433 /// // One second less than the maximum offset results in a failure at the
1434 /// // maximum datetime boundary.
1435 /// let tz = Offset::from_seconds(93_598).unwrap().to_time_zone();
1436 /// assert!(dt.to_zoned_datetime(tz).is_err());
1437 /// ```
1438 ///
1439 /// This behavior exists because it guarantees that every possible
1440 /// `ZonedDateTime` value can be converted into a civil datetime, but not
1441 /// every possible combination of civil datetime and offset can be
1442 /// converted into a `ZonedDateTime` value. There isn't a way to make every
1443 /// possible roundtrip lossless in both directions, so Jiff chooses to
1444 /// ensure that there is always a way to convert a `ZonedDateTime` instant
1445 /// to a human readable wall clock time.
1446 #[inline]
1447 pub fn in_tz(self, time_zone_name: &str) -> Result<ZonedDateTime, Error> {
1448 let tz = crate::tz::db().get(time_zone_name)?;
1449 self.to_zoned_datetime(tz)
1450 }
1451
1452 /// Converts a civil datetime to a [`ZonedDateTime`] datetime by adding the
1453 /// given [`TimeZone`].
1454 ///
1455 /// In some cases, a civil datetime may be ambiguous in a
1456 /// particular time zone. This routine automatically utilizes the
1457 /// [`Disambiguation::Compatible`](crate::tz::Disambiguation) strategy
1458 /// for resolving ambiguities. That is, if a civil datetime occurs in a
1459 /// backward transition (called a fold), then the earlier time is selected.
1460 /// Or if a civil datetime occurs in a forward transition (called a gap),
1461 /// then the later time is selected.
1462 ///
1463 /// To convert a datetime to a `ZonedDateTime` using a different
1464 /// disambiguation strategy, use
1465 /// [`TimeZone::to_ambiguous_zoned_datetime`].
1466 ///
1467 /// In the common case of a time zone being represented as a name string,
1468 /// like `Australia/Hobart`, consider using [`DateTime::in_tz`]
1469 /// instead.
1470 ///
1471 /// # Errors
1472 ///
1473 /// This returns an error if this datetime could not be represented as an
1474 /// instant. This can occur in some cases near the minimum and maximum
1475 /// boundaries of a `DateTime`.
1476 ///
1477 /// # Example
1478 ///
1479 /// This example shows how to create a zoned value with a fixed time zone
1480 /// offset:
1481 ///
1482 /// ```
1483 /// use jiff::{civil::date, tz::{self, TimeZone}};
1484 ///
1485 /// let tz = TimeZone::fixed(tz::offset(-4));
1486 /// let zdt = date(2024, 6, 20).at(17, 3, 0, 0).to_zoned_datetime(tz)?;
1487 /// // A time zone annotation is still included in the printable version
1488 /// // of the ZonedDateTime value, but it is fixed to a particular offset.
1489 /// assert_eq!(zdt.to_string(), "2024-06-20T17:03:00-04:00[-04:00]");
1490 ///
1491 /// # Ok::<(), Box<dyn std::error::Error>>(())
1492 /// ```
1493 ///
1494 /// # Example: POSIX time zone strings
1495 ///
1496 /// And this example shows how to create a time zone from a POSIX time
1497 /// zone string that describes the transition to and from daylight saving
1498 /// time for `America/St_Johns`. In particular, this rule uses non-zero
1499 /// minutes, which is atypical.
1500 ///
1501 /// ```
1502 /// use jiff::{civil::date, tz::TimeZone};
1503 ///
1504 /// let tz = TimeZone::posix("NST3:30NDT,M3.2.0,M11.1.0")?;
1505 /// let zdt = date(2024, 6, 20).at(17, 3, 0, 0).to_zoned_datetime(tz)?;
1506 /// // There isn't any agreed upon mechanism for transmitting a POSIX time
1507 /// // zone string within an RFC 9557 TZ annotation, so Jiff just emits the
1508 /// // offset. In practice, POSIX TZ strings are rarely user facing anyway.
1509 /// // (They are still in widespread use as an implementation detail of the
1510 /// // IANA Time Zone Database however.)
1511 /// assert_eq!(zdt.to_string(), "2024-06-20T17:03:00-02:30[-02:30]");
1512 ///
1513 /// # Ok::<(), Box<dyn std::error::Error>>(())
1514 /// ```
1515 #[inline]
1516 pub fn to_zoned_datetime(
1517 self,
1518 tz: TimeZone,
1519 ) -> Result<ZonedDateTime, Error> {
1520 use crate::tz::AmbiguousOffset;
1521
1522 // It's pretty disappointing that we do this instead of the
1523 // simpler:
1524 //
1525 // tz.into_ambiguous_zoned_datetime(self).compatible()
1526 //
1527 // Below, in the common case of an unambiguous datetime,
1528 // we avoid doing the work to re-derive the datetime *and*
1529 // offset from the timestamp we find from tzdb. In particular,
1530 // `ZonedDateTime::new` does this work given a timestamp and a time
1531 // zone. But we circumvent `ZonedDateTime::new` and use a special
1532 // `ZonedDateTime::from_parts` crate-internal constructor to handle
1533 // this case.
1534 //
1535 // Ideally we could do this in `AmbiguousZonedDateTime::compatible`
1536 // itself, but it turns out that it doesn't always work.
1537 // Namely, that API supports providing an unambiguous
1538 // offset even when the civil datetime is within a
1539 // DST transition. In that case, once the timestamp
1540 // is resolved, the offset given might actually
1541 // change. See `2024-03-11T02:02[America/New_York]`
1542 // example for `AlwaysOffset` conflict resolution on
1543 // `ZonedDateTimeWith::disambiguation`.
1544 //
1545 // But the optimization works here because if we get an
1546 // unambiguous offset from tzdb, then we know it isn't in a DST
1547 // transition and that it won't change with the timestamp.
1548 //
1549 // This ends up saving a fair bit of cycles re-computing
1550 // the offset (which requires another tzdb lookup) and
1551 // re-generating the civil datetime from the timestamp for the
1552 // re-computed offset. This helps the
1553 // `civil_datetime_to_timestamp_tzdb_lookup/zoneinfo/jiff`
1554 // micro-benchmark quite a bit.
1555 let dt = self;
1556 let amb_ts = tz.to_ambiguous_timestamp(dt);
1557 let (offset, ts, dt) = match amb_ts.offset() {
1558 AmbiguousOffset::Unambiguous { offset } => {
1559 let ts = offset.to_timestamp(dt)?;
1560 (offset, ts, dt)
1561 }
1562 AmbiguousOffset::Gap { before, .. } => {
1563 let ts = before.to_timestamp(dt)?;
1564 let offset = tz.to_offset(ts);
1565 let dt = offset.to_datetime(ts);
1566 (offset, ts, dt)
1567 }
1568 AmbiguousOffset::Fold { before, .. } => {
1569 let ts = before.to_timestamp(dt)?;
1570 let offset = tz.to_offset(ts);
1571 let dt = offset.to_datetime(ts);
1572 (offset, ts, dt)
1573 }
1574 };
1575 Ok(ZonedDateTime::from_parts(ts, dt, offset, tz))
1576 }
1577
1578 /// Add the given span of time to this datetime. If the sum would overflow
1579 /// the minimum or maximum datetime values, then an error is returned.
1580 ///
1581 /// This operation accepts three different duration types: [`Span`],
1582 /// [`SignedDuration`] or [`std::time::Duration`]. This is achieved via
1583 /// `From` trait implementations for the [`DateTimeArithmetic`] type.
1584 ///
1585 /// # Properties
1586 ///
1587 /// This routine is _not_ reversible because some additions may
1588 /// be ambiguous. For example, adding `1 month` to the datetime
1589 /// `2024-03-31T00:00:00` will produce `2024-04-30T00:00:00` since April
1590 /// has only 30 days in a month. Moreover, subtracting `1 month` from
1591 /// `2024-04-30T00:00:00` will produce `2024-03-30T00:00:00`, which is not
1592 /// the date we started with.
1593 ///
1594 /// If spans of time are limited to units of days (or less), then this
1595 /// routine _is_ reversible. This also implies that all operations with a
1596 /// [`SignedDuration`] or a [`std::time::Duration`] are reversible.
1597 ///
1598 /// # Errors
1599 ///
1600 /// If the span added to this datetime would result in a datetime that
1601 /// exceeds the range of a `DateTime`, then this will return an error.
1602 ///
1603 /// # Example
1604 ///
1605 /// This shows a few examples of adding spans of time to various dates.
1606 /// We make use of the [`ToSpan`](crate::ToSpan) trait for convenient
1607 /// creation of spans.
1608 ///
1609 /// ```
1610 /// use jiff::{civil::date, ToSpan};
1611 ///
1612 /// let dt = date(1995, 12, 7).at(3, 24, 30, 3_500);
1613 /// let got = dt.checked_add(20.years().months(4).nanoseconds(500))?;
1614 /// assert_eq!(got, date(2016, 4, 7).at(3, 24, 30, 4_000));
1615 ///
1616 /// let dt = date(2019, 1, 31).at(15, 30, 0, 0);
1617 /// let got = dt.checked_add(1.months())?;
1618 /// assert_eq!(got, date(2019, 2, 28).at(15, 30, 0, 0));
1619 ///
1620 /// # Ok::<(), Box<dyn std::error::Error>>(())
1621 /// ```
1622 ///
1623 /// # Example: available via addition operator
1624 ///
1625 /// This routine can be used via the `+` operator. Note though that if it
1626 /// fails, it will result in a panic.
1627 ///
1628 /// ```
1629 /// use jiff::{civil::date, ToSpan};
1630 ///
1631 /// let dt = date(1995, 12, 7).at(3, 24, 30, 3_500);
1632 /// let got = dt + 20.years().months(4).nanoseconds(500);
1633 /// assert_eq!(got, date(2016, 4, 7).at(3, 24, 30, 4_000));
1634 /// ```
1635 ///
1636 /// # Example: negative spans are supported
1637 ///
1638 /// ```
1639 /// use jiff::{civil::date, ToSpan};
1640 ///
1641 /// let dt = date(2024, 3, 31).at(19, 5, 59, 999_999_999);
1642 /// assert_eq!(
1643 /// dt.checked_add(-1.months())?,
1644 /// date(2024, 2, 29).at(19, 5, 59, 999_999_999),
1645 /// );
1646 ///
1647 /// # Ok::<(), Box<dyn std::error::Error>>(())
1648 /// ```
1649 ///
1650 /// # Example: error on overflow
1651 ///
1652 /// ```
1653 /// use jiff::{civil::date, ToSpan};
1654 ///
1655 /// let dt = date(2024, 3, 31).at(13, 13, 13, 13);
1656 /// assert!(dt.checked_add(9000.years()).is_err());
1657 /// assert!(dt.checked_add(-19000.years()).is_err());
1658 /// ```
1659 ///
1660 /// # Example: adding absolute durations
1661 ///
1662 /// This shows how to add signed and unsigned absolute durations to a
1663 /// `DateTime`.
1664 ///
1665 /// ```
1666 /// use std::time::Duration;
1667 ///
1668 /// use jiff::{civil::date, SignedDuration};
1669 ///
1670 /// let dt = date(2024, 2, 29).at(0, 0, 0, 0);
1671 ///
1672 /// let dur = SignedDuration::from_hours(25);
1673 /// assert_eq!(dt.checked_add(dur)?, date(2024, 3, 1).at(1, 0, 0, 0));
1674 /// assert_eq!(dt.checked_add(-dur)?, date(2024, 2, 27).at(23, 0, 0, 0));
1675 ///
1676 /// let dur = Duration::from_secs(25 * 60 * 60);
1677 /// assert_eq!(dt.checked_add(dur)?, date(2024, 3, 1).at(1, 0, 0, 0));
1678 /// // One cannot negate an unsigned duration,
1679 /// // but you can subtract it!
1680 /// assert_eq!(dt.checked_sub(dur)?, date(2024, 2, 27).at(23, 0, 0, 0));
1681 ///
1682 /// # Ok::<(), Box<dyn std::error::Error>>(())
1683 /// ```
1684 #[inline]
1685 pub fn checked_add<A: Into<DateTimeArithmetic>>(
1686 self,
1687 duration: A,
1688 ) -> Result<DateTime, Error> {
1689 let duration: DateTimeArithmetic = duration.into();
1690 duration.checked_add(self)
1691 }
1692
1693 #[inline]
1694 fn checked_add_span(self, span: &Span) -> Result<DateTime, Error> {
1695 let (old_date, old_time) = (self.date(), self.time());
1696 let units = span.units();
1697 match (units.only_calendar().is_empty(), units.only_time().is_empty())
1698 {
1699 (true, true) => Ok(self),
1700 (false, true) => {
1701 let new_date = old_date
1702 .checked_add(span)
1703 .context(E::FailedAddSpanDate)?;
1704 Ok(DateTime::from_parts(new_date, old_time))
1705 }
1706 (true, false) => {
1707 let (new_time, leftovers) = old_time
1708 .overflowing_add(span)
1709 .context(E::FailedAddSpanTime)?;
1710 let new_date = old_date
1711 .checked_add(leftovers)
1712 .context(E::FailedAddSpanOverflowing)?;
1713 Ok(DateTime::from_parts(new_date, new_time))
1714 }
1715 (false, false) => self.checked_add_span_general(span),
1716 }
1717 }
1718
1719 #[inline(never)]
1720 #[cold]
1721 fn checked_add_span_general(self, span: &Span) -> Result<DateTime, Error> {
1722 let (old_date, old_time) = (self.date(), self.time());
1723 let span_date = span.without_lower(Unit::Day);
1724 let span_time = span.only_lower(Unit::Day);
1725
1726 let (new_time, leftovers) = old_time
1727 .overflowing_add(&span_time)
1728 .context(E::FailedAddSpanTime)?;
1729 let new_date =
1730 old_date.checked_add(span_date).context(E::FailedAddSpanDate)?;
1731 let new_date = new_date
1732 .checked_add(leftovers)
1733 .context(E::FailedAddSpanOverflowing)?;
1734 Ok(DateTime::from_parts(new_date, new_time))
1735 }
1736
1737 #[inline]
1738 fn checked_add_duration(
1739 self,
1740 duration: SignedDuration,
1741 ) -> Result<DateTime, Error> {
1742 let (date, time) = (self.date(), self.time());
1743 let (new_time, leftovers) = time.overflowing_add_duration(duration)?;
1744 let new_date = date
1745 .checked_add(leftovers)
1746 .context(E::FailedAddDurationOverflowing)?;
1747 Ok(DateTime::from_parts(new_date, new_time))
1748 }
1749
1750 /// This routine is identical to [`DateTime::checked_add`] with the
1751 /// duration negated.
1752 ///
1753 /// # Errors
1754 ///
1755 /// This has the same error conditions as [`DateTime::checked_add`].
1756 ///
1757 /// # Example
1758 ///
1759 /// This routine can be used via the `-` operator. Note though that if it
1760 /// fails, it will result in a panic.
1761 ///
1762 /// ```
1763 /// use std::time::Duration;
1764 ///
1765 /// use jiff::{civil::date, SignedDuration, ToSpan};
1766 ///
1767 /// let dt = date(1995, 12, 7).at(3, 24, 30, 3_500);
1768 /// assert_eq!(
1769 /// dt - 20.years().months(4).nanoseconds(500),
1770 /// date(1975, 8, 7).at(3, 24, 30, 3_000),
1771 /// );
1772 ///
1773 /// let dur = SignedDuration::new(24 * 60 * 60, 3_500);
1774 /// assert_eq!(dt - dur, date(1995, 12, 6).at(3, 24, 30, 0));
1775 ///
1776 /// let dur = Duration::new(24 * 60 * 60, 3_500);
1777 /// assert_eq!(dt - dur, date(1995, 12, 6).at(3, 24, 30, 0));
1778 ///
1779 /// # Ok::<(), Box<dyn std::error::Error>>(())
1780 /// ```
1781 #[inline]
1782 pub fn checked_sub<A: Into<DateTimeArithmetic>>(
1783 self,
1784 duration: A,
1785 ) -> Result<DateTime, Error> {
1786 let duration: DateTimeArithmetic = duration.into();
1787 duration.checked_neg().and_then(|dta| dta.checked_add(self))
1788 }
1789
1790 /// This routine is identical to [`DateTime::checked_add`], except the
1791 /// result saturates on overflow. That is, instead of overflow, either
1792 /// [`DateTime::MIN`] or [`DateTime::MAX`] is returned.
1793 ///
1794 /// # Example
1795 ///
1796 /// ```
1797 /// use jiff::{civil::{DateTime, date}, SignedDuration, ToSpan};
1798 ///
1799 /// let dt = date(2024, 3, 31).at(13, 13, 13, 13);
1800 /// assert_eq!(DateTime::MAX, dt.saturating_add(9000.years()));
1801 /// assert_eq!(DateTime::MIN, dt.saturating_add(-19000.years()));
1802 /// assert_eq!(DateTime::MAX, dt.saturating_add(SignedDuration::MAX));
1803 /// assert_eq!(DateTime::MIN, dt.saturating_add(SignedDuration::MIN));
1804 /// assert_eq!(DateTime::MAX, dt.saturating_add(std::time::Duration::MAX));
1805 /// ```
1806 #[inline]
1807 pub fn saturating_add<A: Into<DateTimeArithmetic>>(
1808 self,
1809 duration: A,
1810 ) -> DateTime {
1811 let duration: DateTimeArithmetic = duration.into();
1812 self.checked_add(duration).unwrap_or_else(|_| {
1813 if duration.is_negative() { DateTime::MIN } else { DateTime::MAX }
1814 })
1815 }
1816
1817 /// This routine is identical to [`DateTime::saturating_add`] with the span
1818 /// parameter negated.
1819 ///
1820 /// # Example
1821 ///
1822 /// ```
1823 /// use jiff::{civil::{DateTime, date}, SignedDuration, ToSpan};
1824 ///
1825 /// let dt = date(2024, 3, 31).at(13, 13, 13, 13);
1826 /// assert_eq!(DateTime::MIN, dt.saturating_sub(19000.years()));
1827 /// assert_eq!(DateTime::MAX, dt.saturating_sub(-9000.years()));
1828 /// assert_eq!(DateTime::MIN, dt.saturating_sub(SignedDuration::MAX));
1829 /// assert_eq!(DateTime::MAX, dt.saturating_sub(SignedDuration::MIN));
1830 /// assert_eq!(DateTime::MIN, dt.saturating_sub(std::time::Duration::MAX));
1831 /// ```
1832 #[inline]
1833 pub fn saturating_sub<A: Into<DateTimeArithmetic>>(
1834 self,
1835 duration: A,
1836 ) -> DateTime {
1837 let duration: DateTimeArithmetic = duration.into();
1838 let Ok(duration) = duration.checked_neg() else {
1839 return DateTime::MIN;
1840 };
1841 self.saturating_add(duration)
1842 }
1843
1844 /// Returns a span representing the elapsed time from this datetime until
1845 /// the given `other` datetime.
1846 ///
1847 /// When `other` occurs before this datetime, then the span returned will
1848 /// be negative.
1849 ///
1850 /// Depending on the input provided, the span returned is rounded. It may
1851 /// also be balanced up to bigger units than the default. By default, the
1852 /// span returned is balanced such that the biggest possible unit is days.
1853 /// This default is an API guarantee. Users can rely on the default not
1854 /// returning any calendar units bigger than days in the default
1855 /// configuration.
1856 ///
1857 /// This operation is configured by providing a [`DateTimeDifference`]
1858 /// value. Since this routine accepts anything that implements
1859 /// `Into<DateTimeDifference>`, once can pass a `DateTime` directly.
1860 /// One can also pass a `(Unit, DateTime)`, where `Unit` is treated as
1861 /// [`DateTimeDifference::largest`].
1862 ///
1863 /// # Properties
1864 ///
1865 /// It is guaranteed that if the returned span is subtracted from `other`,
1866 /// and if no rounding is requested, and if the largest unit requested is
1867 /// at most `Unit::Day`, then the original datetime will be returned.
1868 ///
1869 /// This routine is equivalent to `self.since(other).map(|span| -span)`
1870 /// if no rounding options are set. If rounding options are set, then
1871 /// it's equivalent to
1872 /// `self.since(other_without_rounding_options).map(|span| -span)`,
1873 /// followed by a call to [`Span::round`] with the appropriate rounding
1874 /// options set. This is because the negation of a span can result in
1875 /// different rounding results depending on the rounding mode.
1876 ///
1877 /// # Errors
1878 ///
1879 /// An error can occur in some cases when the requested configuration would
1880 /// result in a span that is beyond allowable limits. For example, the
1881 /// nanosecond component of a span cannot the span of time between the
1882 /// minimum and maximum datetime supported by Jiff. Therefore, if one
1883 /// requests a span with its largest unit set to [`Unit::Nanosecond`], then
1884 /// it's possible for this routine to fail.
1885 ///
1886 /// It is guaranteed that if one provides a datetime with the default
1887 /// [`DateTimeDifference`] configuration, then this routine will never
1888 /// fail.
1889 ///
1890 /// # Example
1891 ///
1892 /// ```
1893 /// use jiff::{civil::date, ToSpan};
1894 ///
1895 /// let earlier = date(2006, 8, 24).at(22, 30, 0, 0);
1896 /// let later = date(2019, 1, 31).at(21, 0, 0, 0);
1897 /// assert_eq!(
1898 /// earlier.until(later)?,
1899 /// 4542.days().hours(22).minutes(30).fieldwise(),
1900 /// );
1901 ///
1902 /// // Flipping the dates is fine, but you'll get a negative span.
1903 /// assert_eq!(
1904 /// later.until(earlier)?,
1905 /// -4542.days().hours(22).minutes(30).fieldwise(),
1906 /// );
1907 ///
1908 /// # Ok::<(), Box<dyn std::error::Error>>(())
1909 /// ```
1910 ///
1911 /// # Example: using bigger units
1912 ///
1913 /// This example shows how to expand the span returned to bigger units.
1914 /// This makes use of a `From<(Unit, DateTime)> for DateTimeDifference`
1915 /// trait implementation.
1916 ///
1917 /// ```
1918 /// use jiff::{civil::date, Unit, ToSpan};
1919 ///
1920 /// let dt1 = date(1995, 12, 07).at(3, 24, 30, 3500);
1921 /// let dt2 = date(2019, 01, 31).at(15, 30, 0, 0);
1922 ///
1923 /// // The default limits durations to using "days" as the biggest unit.
1924 /// let span = dt1.until(dt2)?;
1925 /// assert_eq!(span.to_string(), "P8456DT12H5M29.9999965S");
1926 ///
1927 /// // But we can ask for units all the way up to years.
1928 /// let span = dt1.until((Unit::Year, dt2))?;
1929 /// assert_eq!(span.to_string(), "P23Y1M24DT12H5M29.9999965S");
1930 /// # Ok::<(), Box<dyn std::error::Error>>(())
1931 /// ```
1932 ///
1933 /// # Example: rounding the result
1934 ///
1935 /// This shows how one might find the difference between two datetimes and
1936 /// have the result rounded such that sub-seconds are removed.
1937 ///
1938 /// In this case, we need to hand-construct a [`DateTimeDifference`]
1939 /// in order to gain full configurability.
1940 ///
1941 /// ```
1942 /// use jiff::{civil::{DateTimeDifference, date}, Unit, ToSpan};
1943 ///
1944 /// let dt1 = date(1995, 12, 07).at(3, 24, 30, 3500);
1945 /// let dt2 = date(2019, 01, 31).at(15, 30, 0, 0);
1946 ///
1947 /// let span = dt1.until(
1948 /// DateTimeDifference::from(dt2).smallest(Unit::Second),
1949 /// )?;
1950 /// assert_eq!(format!("{span:#}"), "8456d 12h 5m 29s");
1951 ///
1952 /// // We can combine smallest and largest units too!
1953 /// let span = dt1.until(
1954 /// DateTimeDifference::from(dt2)
1955 /// .smallest(Unit::Second)
1956 /// .largest(Unit::Year),
1957 /// )?;
1958 /// assert_eq!(span.to_string(), "P23Y1M24DT12H5M29S");
1959 /// # Ok::<(), Box<dyn std::error::Error>>(())
1960 /// ```
1961 ///
1962 /// # Example: units biggers than days inhibit reversibility
1963 ///
1964 /// If you ask for units bigger than days, then subtracting the span
1965 /// returned from the `other` datetime is not guaranteed to result in the
1966 /// original datetime. For example:
1967 ///
1968 /// ```
1969 /// use jiff::{civil::date, Unit, ToSpan};
1970 ///
1971 /// let dt1 = date(2024, 3, 2).at(0, 0, 0, 0);
1972 /// let dt2 = date(2024, 5, 1).at(0, 0, 0, 0);
1973 ///
1974 /// let span = dt1.until((Unit::Month, dt2))?;
1975 /// assert_eq!(span, 1.month().days(29).fieldwise());
1976 /// let maybe_original = dt2.checked_sub(span)?;
1977 /// // Not the same as the original datetime!
1978 /// assert_eq!(maybe_original, date(2024, 3, 3).at(0, 0, 0, 0));
1979 ///
1980 /// // But in the default configuration, days are always the biggest unit
1981 /// // and reversibility is guaranteed.
1982 /// let span = dt1.until(dt2)?;
1983 /// assert_eq!(span, 60.days().fieldwise());
1984 /// let is_original = dt2.checked_sub(span)?;
1985 /// assert_eq!(is_original, dt1);
1986 ///
1987 /// # Ok::<(), Box<dyn std::error::Error>>(())
1988 /// ```
1989 ///
1990 /// This occurs because span are added as if by adding the biggest units
1991 /// first, and then the smaller units. Because months vary in length,
1992 /// their meaning can change depending on how the span is added. In this
1993 /// case, adding one month to `2024-03-02` corresponds to 31 days, but
1994 /// subtracting one month from `2024-05-01` corresponds to 30 days.
1995 #[inline]
1996 pub fn until<A: Into<DateTimeDifference>>(
1997 self,
1998 other: A,
1999 ) -> Result<Span, Error> {
2000 let args: DateTimeDifference = other.into();
2001 let span = args.until_with_largest_unit(self)?;
2002 if args.rounding_may_change_span() {
2003 span.round(args.round.relative(self))
2004 } else {
2005 Ok(span)
2006 }
2007 }
2008
2009 /// This routine is identical to [`DateTime::until`], but the order of the
2010 /// parameters is flipped.
2011 ///
2012 /// # Errors
2013 ///
2014 /// This has the same error conditions as [`DateTime::until`].
2015 ///
2016 /// # Example
2017 ///
2018 /// This routine can be used via the `-` operator. Since the default
2019 /// configuration is used and because a `Span` can represent the difference
2020 /// between any two possible datetimes, it will never panic.
2021 ///
2022 /// ```
2023 /// use jiff::{civil::date, ToSpan};
2024 ///
2025 /// let earlier = date(2006, 8, 24).at(22, 30, 0, 0);
2026 /// let later = date(2019, 1, 31).at(21, 0, 0, 0);
2027 /// assert_eq!(
2028 /// later - earlier,
2029 /// 4542.days().hours(22).minutes(30).fieldwise(),
2030 /// );
2031 /// ```
2032 #[inline]
2033 pub fn since<A: Into<DateTimeDifference>>(
2034 self,
2035 other: A,
2036 ) -> Result<Span, Error> {
2037 let args: DateTimeDifference = other.into();
2038 let span = -args.until_with_largest_unit(self)?;
2039 if args.rounding_may_change_span() {
2040 span.round(args.round.relative(self))
2041 } else {
2042 Ok(span)
2043 }
2044 }
2045
2046 /// Returns an absolute duration representing the elapsed time from this
2047 /// datetime until the given `other` datetime.
2048 ///
2049 /// When `other` occurs before this datetime, then the duration returned
2050 /// will be negative.
2051 ///
2052 /// Unlike [`DateTime::until`], this returns a duration corresponding to a
2053 /// 96-bit integer of nanoseconds between two datetimes.
2054 ///
2055 /// # Fallibility
2056 ///
2057 /// This routine never panics or returns an error. Since there are no
2058 /// configuration options that can be incorrectly provided, no error is
2059 /// possible when calling this routine. In contrast, [`DateTime::until`]
2060 /// can return an error in some cases due to misconfiguration. But like
2061 /// this routine, [`DateTime::until`] never panics or returns an error in
2062 /// its default configuration.
2063 ///
2064 /// # When should I use this versus [`DateTime::until`]?
2065 ///
2066 /// See the type documentation for [`SignedDuration`] for the section on
2067 /// when one should use [`Span`] and when one should use `SignedDuration`.
2068 /// In short, use `Span` (and therefore `DateTime::until`) unless you have
2069 /// a specific reason to do otherwise.
2070 ///
2071 /// # Example
2072 ///
2073 /// ```
2074 /// use jiff::{civil::date, SignedDuration};
2075 ///
2076 /// let earlier = date(2006, 8, 24).at(22, 30, 0, 0);
2077 /// let later = date(2019, 1, 31).at(21, 0, 0, 0);
2078 /// assert_eq!(
2079 /// earlier.duration_until(later),
2080 /// SignedDuration::from_hours(4542 * 24)
2081 /// + SignedDuration::from_hours(22)
2082 /// + SignedDuration::from_mins(30),
2083 /// );
2084 /// // Flipping the datetimes is fine, but you'll get a negative duration.
2085 /// assert_eq!(
2086 /// later.duration_until(earlier),
2087 /// -SignedDuration::from_hours(4542 * 24)
2088 /// - SignedDuration::from_hours(22)
2089 /// - SignedDuration::from_mins(30),
2090 /// );
2091 /// ```
2092 ///
2093 /// # Example: difference with [`DateTime::until`]
2094 ///
2095 /// The main difference between this routine and `DateTime::until` is that
2096 /// the latter can return units other than a 96-bit integer of nanoseconds.
2097 /// While a 96-bit integer of nanoseconds can be converted into other units
2098 /// like hours, this can only be done for uniform units. (Uniform units are
2099 /// units for which each individual unit always corresponds to the same
2100 /// elapsed time regardless of the datetime it is relative to.) This can't
2101 /// be done for units like years or months.
2102 ///
2103 /// ```
2104 /// use jiff::{civil::date, SignedDuration, Span, SpanRound, ToSpan, Unit};
2105 ///
2106 /// let dt1 = date(2024, 1, 1).at(0, 0, 0, 0);
2107 /// let dt2 = date(2025, 4, 1).at(0, 0, 0, 0);
2108 ///
2109 /// let span = dt1.until((Unit::Year, dt2))?;
2110 /// assert_eq!(span, 1.year().months(3).fieldwise());
2111 ///
2112 /// let duration = dt1.duration_until(dt2);
2113 /// assert_eq!(duration, SignedDuration::from_hours(456 * 24));
2114 /// // There's no way to extract years or months from the signed
2115 /// // duration like one might extract hours (because every hour
2116 /// // is the same length). Instead, you actually have to convert
2117 /// // it to a span and then balance it by providing a relative date!
2118 /// let options = SpanRound::new().largest(Unit::Year).relative(dt1);
2119 /// let span = Span::try_from(duration)?.round(options)?;
2120 /// assert_eq!(span, 1.year().months(3).fieldwise());
2121 ///
2122 /// # Ok::<(), Box<dyn std::error::Error>>(())
2123 /// ```
2124 ///
2125 /// # Example: getting an unsigned duration
2126 ///
2127 /// If you're looking to find the duration between two datetimes as a
2128 /// [`std::time::Duration`], you'll need to use this method to get a
2129 /// [`SignedDuration`] and then convert it to a `std::time::Duration`:
2130 ///
2131 /// ```
2132 /// use std::time::Duration;
2133 ///
2134 /// use jiff::civil::date;
2135 ///
2136 /// let dt1 = date(2024, 7, 1).at(0, 0, 0, 0);
2137 /// let dt2 = date(2024, 8, 1).at(0, 0, 0, 0);
2138 /// let duration = Duration::try_from(dt1.duration_until(dt2))?;
2139 /// assert_eq!(duration, Duration::from_secs(31 * 24 * 60 * 60));
2140 ///
2141 /// // Note that unsigned durations cannot represent all
2142 /// // possible differences! If the duration would be negative,
2143 /// // then the conversion fails:
2144 /// assert!(Duration::try_from(dt2.duration_until(dt1)).is_err());
2145 ///
2146 /// # Ok::<(), Box<dyn std::error::Error>>(())
2147 /// ```
2148 #[inline]
2149 pub fn duration_until(self, other: DateTime) -> SignedDuration {
2150 SignedDuration::datetime_until(self, other)
2151 }
2152
2153 /// This routine is identical to [`DateTime::duration_until`], but the
2154 /// order of the parameters is flipped.
2155 ///
2156 /// # Example
2157 ///
2158 /// ```
2159 /// use jiff::{civil::date, SignedDuration};
2160 ///
2161 /// let earlier = date(2006, 8, 24).at(22, 30, 0, 0);
2162 /// let later = date(2019, 1, 31).at(21, 0, 0, 0);
2163 /// assert_eq!(
2164 /// later.duration_since(earlier),
2165 /// SignedDuration::from_hours(4542 * 24)
2166 /// + SignedDuration::from_hours(22)
2167 /// + SignedDuration::from_mins(30),
2168 /// );
2169 /// ```
2170 #[inline]
2171 pub fn duration_since(self, other: DateTime) -> SignedDuration {
2172 SignedDuration::datetime_until(other, self)
2173 }
2174
2175 /// Rounds this datetime according to the [`DateTimeRound`] configuration
2176 /// given.
2177 ///
2178 /// The principal option is [`DateTimeRound::smallest`], which allows one
2179 /// to configure the smallest units in the returned datetime. Rounding
2180 /// is what determines whether that unit should keep its current value
2181 /// or whether it should be incremented. Moreover, the amount it should
2182 /// be incremented can be configured via [`DateTimeRound::increment`].
2183 /// Finally, the rounding strategy itself can be configured via
2184 /// [`DateTimeRound::mode`].
2185 ///
2186 /// Note that this routine is generic and accepts anything that
2187 /// implements `Into<DateTimeRound>`. Some notable implementations are:
2188 ///
2189 /// * `From<Unit> for DateTimeRound`, which will automatically create a
2190 /// `DateTimeRound::new().smallest(unit)` from the unit provided.
2191 /// * `From<(Unit, i64)> for DateTimeRound`, which will automatically
2192 /// create a `DateTimeRound::new().smallest(unit).increment(number)` from
2193 /// the unit and increment provided.
2194 ///
2195 /// # Errors
2196 ///
2197 /// This returns an error if the smallest unit configured on the given
2198 /// [`DateTimeRound`] is bigger than days. An error is also returned if
2199 /// the rounding increment is greater than 1 when the units are days.
2200 /// (Currently, rounding to the nearest week, month or year is not
2201 /// supported.)
2202 ///
2203 /// When the smallest unit is less than days, the rounding increment must
2204 /// divide evenly into the next highest unit after the smallest unit
2205 /// configured (and must not be equivalent to it). For example, if the
2206 /// smallest unit is [`Unit::Nanosecond`], then *some* of the valid values
2207 /// for the rounding increment are `1`, `2`, `4`, `5`, `100` and `500`.
2208 /// Namely, any integer that divides evenly into `1,000` nanoseconds since
2209 /// there are `1,000` nanoseconds in the next highest unit (microseconds).
2210 ///
2211 /// This can also return an error in some cases where rounding would
2212 /// require arithmetic that exceeds the maximum datetime value.
2213 ///
2214 /// # Example
2215 ///
2216 /// This is a basic example that demonstrates rounding a datetime to the
2217 /// nearest day. This also demonstrates calling this method with the
2218 /// smallest unit directly, instead of constructing a `DateTimeRound`
2219 /// manually.
2220 ///
2221 /// ```
2222 /// use jiff::{civil::date, Unit};
2223 ///
2224 /// let dt = date(2024, 6, 19).at(15, 0, 0, 0);
2225 /// assert_eq!(dt.round(Unit::Day)?, date(2024, 6, 20).at(0, 0, 0, 0));
2226 /// let dt = date(2024, 6, 19).at(10, 0, 0, 0);
2227 /// assert_eq!(dt.round(Unit::Day)?, date(2024, 6, 19).at(0, 0, 0, 0));
2228 ///
2229 /// # Ok::<(), Box<dyn std::error::Error>>(())
2230 /// ```
2231 ///
2232 /// # Example: changing the rounding mode
2233 ///
2234 /// The default rounding mode is [`RoundMode::HalfExpand`], which
2235 /// breaks ties by rounding away from zero. But other modes like
2236 /// [`RoundMode::Trunc`] can be used too:
2237 ///
2238 /// ```
2239 /// use jiff::{civil::{DateTimeRound, date}, RoundMode, Unit};
2240 ///
2241 /// let dt = date(2024, 6, 19).at(15, 0, 0, 0);
2242 /// assert_eq!(dt.round(Unit::Day)?, date(2024, 6, 20).at(0, 0, 0, 0));
2243 /// // The default will round up to the next day for any time past noon,
2244 /// // but using truncation rounding will always round down.
2245 /// assert_eq!(
2246 /// dt.round(
2247 /// DateTimeRound::new().smallest(Unit::Day).mode(RoundMode::Trunc),
2248 /// )?,
2249 /// date(2024, 6, 19).at(0, 0, 0, 0),
2250 /// );
2251 ///
2252 /// # Ok::<(), Box<dyn std::error::Error>>(())
2253 /// ```
2254 ///
2255 /// # Example: rounding to the nearest 5 minute increment
2256 ///
2257 /// ```
2258 /// use jiff::{civil::date, Unit};
2259 ///
2260 /// // rounds down
2261 /// let dt = date(2024, 6, 19).at(15, 27, 29, 999_999_999);
2262 /// assert_eq!(
2263 /// dt.round((Unit::Minute, 5))?,
2264 /// date(2024, 6, 19).at(15, 25, 0, 0),
2265 /// );
2266 /// // rounds up
2267 /// let dt = date(2024, 6, 19).at(15, 27, 30, 0);
2268 /// assert_eq!(
2269 /// dt.round((Unit::Minute, 5))?,
2270 /// date(2024, 6, 19).at(15, 30, 0, 0),
2271 /// );
2272 ///
2273 /// # Ok::<(), Box<dyn std::error::Error>>(())
2274 /// ```
2275 ///
2276 /// # Example: overflow error
2277 ///
2278 /// This example demonstrates that it's possible for this operation to
2279 /// result in an error from datetime arithmetic overflow.
2280 ///
2281 /// ```
2282 /// use jiff::{civil::DateTime, Unit};
2283 ///
2284 /// let dt = DateTime::MAX;
2285 /// assert!(dt.round(Unit::Day).is_err());
2286 /// ```
2287 ///
2288 /// This occurs because rounding to the nearest day for the maximum
2289 /// datetime would result in rounding up to the next day. But the next day
2290 /// is greater than the maximum, and so this returns an error.
2291 ///
2292 /// If one were to use a rounding mode like [`RoundMode::Trunc`] (which
2293 /// will never round up), always set a correct increment and always used
2294 /// units less than or equal to days, then this routine is guaranteed to
2295 /// never fail:
2296 ///
2297 /// ```
2298 /// use jiff::{civil::{DateTime, DateTimeRound, date}, RoundMode, Unit};
2299 ///
2300 /// let round = DateTimeRound::new()
2301 /// .smallest(Unit::Day)
2302 /// .mode(RoundMode::Trunc);
2303 /// assert_eq!(
2304 /// DateTime::MAX.round(round)?,
2305 /// date(9999, 12, 31).at(0, 0, 0, 0),
2306 /// );
2307 /// assert_eq!(
2308 /// DateTime::MIN.round(round)?,
2309 /// date(-9999, 1, 1).at(0, 0, 0, 0),
2310 /// );
2311 ///
2312 /// # Ok::<(), Box<dyn std::error::Error>>(())
2313 /// ```
2314 #[inline]
2315 pub fn round<R: Into<DateTimeRound>>(
2316 self,
2317 options: R,
2318 ) -> Result<DateTime, Error> {
2319 let options: DateTimeRound = options.into();
2320 options.round(self)
2321 }
2322
2323 /// Return an iterator of periodic datetimes determined by the given span.
2324 ///
2325 /// The given span may be negative, in which case, the iterator will move
2326 /// backwards through time. The iterator won't stop until either the span
2327 /// itself overflows, or it would otherwise exceed the minimum or maximum
2328 /// `DateTime` value.
2329 ///
2330 /// # Example: when to check a glucose monitor
2331 ///
2332 /// When my cat had diabetes, my veterinarian installed a glucose monitor
2333 /// and instructed me to scan it about every 5 hours. This example lists
2334 /// all of the times I need to scan it for the 2 days following its
2335 /// installation:
2336 ///
2337 /// ```
2338 /// use jiff::{civil::datetime, ToSpan};
2339 ///
2340 /// let start = datetime(2023, 7, 15, 16, 30, 0, 0);
2341 /// let end = start.checked_add(2.days())?;
2342 /// let mut scan_times = vec![];
2343 /// for dt in start.series(5.hours()).take_while(|&dt| dt <= end) {
2344 /// scan_times.push(dt);
2345 /// }
2346 /// assert_eq!(scan_times, vec![
2347 /// datetime(2023, 7, 15, 16, 30, 0, 0),
2348 /// datetime(2023, 7, 15, 21, 30, 0, 0),
2349 /// datetime(2023, 7, 16, 2, 30, 0, 0),
2350 /// datetime(2023, 7, 16, 7, 30, 0, 0),
2351 /// datetime(2023, 7, 16, 12, 30, 0, 0),
2352 /// datetime(2023, 7, 16, 17, 30, 0, 0),
2353 /// datetime(2023, 7, 16, 22, 30, 0, 0),
2354 /// datetime(2023, 7, 17, 3, 30, 0, 0),
2355 /// datetime(2023, 7, 17, 8, 30, 0, 0),
2356 /// datetime(2023, 7, 17, 13, 30, 0, 0),
2357 /// ]);
2358 ///
2359 /// # Ok::<(), Box<dyn std::error::Error>>(())
2360 /// ```
2361 #[inline]
2362 pub fn series(self, period: Span) -> DateTimeSeries {
2363 DateTimeSeries { start: self, period, step: 0 }
2364 }
2365
2366 /// Converts this datetime to a nanosecond timestamp assuming a Zulu time
2367 /// zone offset and where all days are exactly 24 hours long.
2368 #[inline]
2369 fn to_duration(self) -> SignedDuration {
2370 let mut dur = SignedDuration::from_civil_days32(
2371 self.date().to_unix_epoch_day().day(),
2372 );
2373 dur += self.time().to_duration();
2374 dur
2375 }
2376
2377 #[inline]
2378 pub(crate) const fn from_jcore(dt: JDateTime) -> DateTime {
2379 DateTime::from_parts(
2380 Date::from_jcore(dt.date()),
2381 Time::from_jcore(dt.time()),
2382 )
2383 }
2384
2385 #[inline]
2386 pub(crate) const fn to_jcore(&self) -> JDateTime {
2387 JDateTime::from_parts(self.date.to_jcore(), self.time.to_jcore())
2388 }
2389}
2390
2391/// Parsing and formatting using a "printf"-style API.
2392impl DateTime {
2393 /// Parses a civil datetime in `input` matching the given `format`.
2394 ///
2395 /// The format string uses a "printf"-style API where conversion
2396 /// specifiers can be used as place holders to match components of
2397 /// a datetime. For details on the specifiers supported, see the
2398 /// [`fmt::strtime`] module documentation.
2399 ///
2400 /// # Errors
2401 ///
2402 /// This returns an error when parsing failed. This might happen because
2403 /// the format string itself was invalid, or because the input didn't match
2404 /// the format string.
2405 ///
2406 /// This also returns an error if there wasn't sufficient information to
2407 /// construct a civil datetime. For example, if an offset wasn't parsed.
2408 ///
2409 /// # Example
2410 ///
2411 /// This example shows how to parse a civil datetime:
2412 ///
2413 /// ```
2414 /// use jiff::civil::DateTime;
2415 ///
2416 /// let dt = DateTime::strptime("%F %H:%M", "2024-07-14 21:14")?;
2417 /// assert_eq!(dt.to_string(), "2024-07-14T21:14:00");
2418 ///
2419 /// # Ok::<(), Box<dyn std::error::Error>>(())
2420 /// ```
2421 #[inline]
2422 pub fn strptime(
2423 format: impl AsRef<[u8]>,
2424 input: impl AsRef<[u8]>,
2425 ) -> Result<DateTime, Error> {
2426 fmt::strtime::parse(format, input).and_then(|tm| tm.to_datetime())
2427 }
2428
2429 /// Formats this civil datetime according to the given `format`.
2430 ///
2431 /// The format string uses a "printf"-style API where conversion
2432 /// specifiers can be used as place holders to format components of
2433 /// a datetime. For details on the specifiers supported, see the
2434 /// [`fmt::strtime`] module documentation.
2435 ///
2436 /// # Errors and panics
2437 ///
2438 /// This will never error or panic. In particular,
2439 /// [lenient mode](crate::fmt::strtime::Config::lenient) is enabled, which
2440 /// means that all possible strings have some non-error interpretation.
2441 /// Note that because of this, and since Jiff may add new conversion
2442 /// specifiers in the future, the behavior of a format string may change
2443 /// when it would otherwise be invalid.
2444 ///
2445 /// To format in a way that surfaces errors, use either
2446 /// [`fmt::strtime::format`] or [`fmt::strtime::BrokenDownTime::format`].
2447 ///
2448 /// # Example
2449 ///
2450 /// This example shows how to format a civil datetime:
2451 ///
2452 /// ```
2453 /// use jiff::civil::date;
2454 ///
2455 /// let dt = date(2024, 7, 15).at(16, 24, 59, 0);
2456 /// let string = dt.strftime("%A, %B %e, %Y at %H:%M:%S").to_string();
2457 /// assert_eq!(string, "Monday, July 15, 2024 at 16:24:59");
2458 /// ```
2459 ///
2460 /// # Example: errors are silently ignored
2461 ///
2462 /// If the formatting string is malformed in some way, then it is silently
2463 /// ignored. For example, when using an invalid formatting directive:
2464 ///
2465 /// ```
2466 /// use jiff::civil::date;
2467 ///
2468 /// let dt = date(2024, 7, 15).at(16, 24, 59, 0);
2469 /// let string = dt.strftime("%Y %").to_string();
2470 /// assert_eq!(string, "2024 %");
2471 /// ```
2472 ///
2473 /// If one wants to surface errors from a formatting string, use a lower
2474 /// level API:
2475 ///
2476 /// ```
2477 /// use jiff::civil::date;
2478 ///
2479 /// let dt = date(2024, 7, 15).at(16, 24, 59, 0);
2480 /// assert_eq!(
2481 /// jiff::fmt::strtime::format("%Y %", dt).unwrap_err().to_string(),
2482 /// "strftime formatting failed: invalid format string, \
2483 /// expected byte after `%`, but found end of format string",
2484 /// );
2485 /// ```
2486 #[inline]
2487 pub fn strftime<'f, F: 'f + ?Sized + AsRef<[u8]>>(
2488 &self,
2489 format: &'f F,
2490 ) -> fmt::strtime::Display<'f> {
2491 fmt::strtime::Display { fmt: format.as_ref(), tm: (*self).into() }
2492 }
2493}
2494
2495impl Default for DateTime {
2496 #[inline]
2497 fn default() -> DateTime {
2498 DateTime::ZERO
2499 }
2500}
2501
2502/// Converts a `DateTime` into a human readable datetime string.
2503///
2504/// (This `Debug` representation currently emits the same string as the
2505/// `Display` representation, but this is not a guarantee.)
2506///
2507/// Options currently supported:
2508///
2509/// * [`std::fmt::Formatter::precision`] can be set to control the precision
2510/// of the fractional second component.
2511///
2512/// # Example
2513///
2514/// ```
2515/// use jiff::civil::date;
2516///
2517/// let dt = date(2024, 6, 15).at(7, 0, 0, 123_000_000);
2518/// assert_eq!(format!("{dt:.6?}"), "2024-06-15T07:00:00.123000");
2519/// // Precision values greater than 9 are clamped to 9.
2520/// assert_eq!(format!("{dt:.300?}"), "2024-06-15T07:00:00.123000000");
2521/// // A precision of 0 implies the entire fractional
2522/// // component is always truncated.
2523/// assert_eq!(format!("{dt:.0?}"), "2024-06-15T07:00:00");
2524///
2525/// # Ok::<(), Box<dyn std::error::Error>>(())
2526/// ```
2527impl core::fmt::Debug for DateTime {
2528 #[inline]
2529 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2530 core::fmt::Display::fmt(self, f)
2531 }
2532}
2533
2534/// Converts a `DateTime` into an ISO 8601 compliant string.
2535///
2536/// # Formatting options supported
2537///
2538/// * [`std::fmt::Formatter::precision`] can be set to control the precision
2539/// of the fractional second component. When not set, the minimum precision
2540/// required to losslessly render the value is used.
2541///
2542/// # Example
2543///
2544/// This shows the default rendering:
2545///
2546/// ```
2547/// use jiff::civil::date;
2548///
2549/// // No fractional seconds:
2550/// let dt = date(2024, 6, 15).at(7, 0, 0, 0);
2551/// assert_eq!(format!("{dt}"), "2024-06-15T07:00:00");
2552///
2553/// // With fractional seconds:
2554/// let dt = date(2024, 6, 15).at(7, 0, 0, 123_000_000);
2555/// assert_eq!(format!("{dt}"), "2024-06-15T07:00:00.123");
2556///
2557/// # Ok::<(), Box<dyn std::error::Error>>(())
2558/// ```
2559///
2560/// # Example: setting the precision
2561///
2562/// ```
2563/// use jiff::civil::date;
2564///
2565/// let dt = date(2024, 6, 15).at(7, 0, 0, 123_000_000);
2566/// assert_eq!(format!("{dt:.6}"), "2024-06-15T07:00:00.123000");
2567/// // Precision values greater than 9 are clamped to 9.
2568/// assert_eq!(format!("{dt:.300}"), "2024-06-15T07:00:00.123000000");
2569/// // A precision of 0 implies the entire fractional
2570/// // component is always truncated.
2571/// assert_eq!(format!("{dt:.0}"), "2024-06-15T07:00:00");
2572///
2573/// # Ok::<(), Box<dyn std::error::Error>>(())
2574/// ```
2575impl core::fmt::Display for DateTime {
2576 #[inline]
2577 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2578 use crate::fmt::StdFmtWrite;
2579
2580 let precision =
2581 f.precision().map(|p| u8::try_from(p).unwrap_or(u8::MAX));
2582 temporal::DateTimePrinter::new()
2583 .precision(precision)
2584 .print_datetime(self, StdFmtWrite(f))
2585 .map_err(|_| core::fmt::Error)
2586 }
2587}
2588
2589impl core::str::FromStr for DateTime {
2590 type Err = Error;
2591
2592 #[inline]
2593 fn from_str(string: &str) -> Result<DateTime, Error> {
2594 DEFAULT_DATETIME_PARSER.parse_datetime(string)
2595 }
2596}
2597
2598/// Converts a [`Date`] to a [`DateTime`] with the time set to midnight.
2599impl From<Date> for DateTime {
2600 #[inline]
2601 fn from(date: Date) -> DateTime {
2602 date.to_datetime(Time::midnight())
2603 }
2604}
2605
2606/// Converts a [`ZonedDateTime`] to a [`DateTime`].
2607impl From<ZonedDateTime> for DateTime {
2608 #[inline]
2609 fn from(zdt: ZonedDateTime) -> DateTime {
2610 zdt.datetime()
2611 }
2612}
2613
2614/// Converts a [`&ZonedDateTime`](ZonedDateTime) to a [`DateTime`].
2615impl<'a> From<&'a ZonedDateTime> for DateTime {
2616 #[inline]
2617 fn from(zdt: &'a ZonedDateTime) -> DateTime {
2618 zdt.datetime()
2619 }
2620}
2621
2622/// Adds a span of time to a datetime.
2623///
2624/// This uses checked arithmetic and panics on overflow. To handle overflow
2625/// without panics, use [`DateTime::checked_add`].
2626impl core::ops::Add<Span> for DateTime {
2627 type Output = DateTime;
2628
2629 #[inline]
2630 fn add(self, rhs: Span) -> DateTime {
2631 self.checked_add(rhs).expect("adding span to datetime overflowed")
2632 }
2633}
2634
2635/// Adds a span of time to a datetime in place.
2636///
2637/// This uses checked arithmetic and panics on overflow. To handle overflow
2638/// without panics, use [`DateTime::checked_add`].
2639impl core::ops::AddAssign<Span> for DateTime {
2640 #[inline]
2641 fn add_assign(&mut self, rhs: Span) {
2642 *self = *self + rhs
2643 }
2644}
2645
2646/// Subtracts a span of time from a datetime.
2647///
2648/// This uses checked arithmetic and panics on overflow. To handle overflow
2649/// without panics, use [`DateTime::checked_sub`].
2650impl core::ops::Sub<Span> for DateTime {
2651 type Output = DateTime;
2652
2653 #[inline]
2654 fn sub(self, rhs: Span) -> DateTime {
2655 self.checked_sub(rhs)
2656 .expect("subtracting span from datetime overflowed")
2657 }
2658}
2659
2660/// Subtracts a span of time from a datetime in place.
2661///
2662/// This uses checked arithmetic and panics on overflow. To handle overflow
2663/// without panics, use [`DateTime::checked_sub`].
2664impl core::ops::SubAssign<Span> for DateTime {
2665 #[inline]
2666 fn sub_assign(&mut self, rhs: Span) {
2667 *self = *self - rhs
2668 }
2669}
2670
2671/// Computes the span of time between two datetimes.
2672///
2673/// This will return a negative span when the datetime being subtracted is
2674/// greater.
2675///
2676/// Since this uses the default configuration for calculating a span between
2677/// two datetimes (no rounding and largest units is days), this will never
2678/// panic or fail in any way. It is guaranteed that the largest non-zero
2679/// unit in the `Span` returned will be days.
2680///
2681/// To configure the largest unit or enable rounding, use [`DateTime::since`].
2682///
2683/// If you need a [`SignedDuration`] representing the span between two civil
2684/// datetimes, then use [`DateTime::duration_since`].
2685impl core::ops::Sub for DateTime {
2686 type Output = Span;
2687
2688 #[inline]
2689 fn sub(self, rhs: DateTime) -> Span {
2690 self.since(rhs).expect("since never fails when given DateTime")
2691 }
2692}
2693
2694/// Adds a signed duration of time to a datetime.
2695///
2696/// This uses checked arithmetic and panics on overflow. To handle overflow
2697/// without panics, use [`DateTime::checked_add`].
2698impl core::ops::Add<SignedDuration> for DateTime {
2699 type Output = DateTime;
2700
2701 #[inline]
2702 fn add(self, rhs: SignedDuration) -> DateTime {
2703 self.checked_add(rhs)
2704 .expect("adding signed duration to datetime overflowed")
2705 }
2706}
2707
2708/// Adds a signed duration of time to a datetime in place.
2709///
2710/// This uses checked arithmetic and panics on overflow. To handle overflow
2711/// without panics, use [`DateTime::checked_add`].
2712impl core::ops::AddAssign<SignedDuration> for DateTime {
2713 #[inline]
2714 fn add_assign(&mut self, rhs: SignedDuration) {
2715 *self = *self + rhs
2716 }
2717}
2718
2719/// Subtracts a signed duration of time from a datetime.
2720///
2721/// This uses checked arithmetic and panics on overflow. To handle overflow
2722/// without panics, use [`DateTime::checked_sub`].
2723impl core::ops::Sub<SignedDuration> for DateTime {
2724 type Output = DateTime;
2725
2726 #[inline]
2727 fn sub(self, rhs: SignedDuration) -> DateTime {
2728 self.checked_sub(rhs)
2729 .expect("subtracting signed duration from datetime overflowed")
2730 }
2731}
2732
2733/// Subtracts a signed duration of time from a datetime in place.
2734///
2735/// This uses checked arithmetic and panics on overflow. To handle overflow
2736/// without panics, use [`DateTime::checked_sub`].
2737impl core::ops::SubAssign<SignedDuration> for DateTime {
2738 #[inline]
2739 fn sub_assign(&mut self, rhs: SignedDuration) {
2740 *self = *self - rhs
2741 }
2742}
2743
2744/// Adds an unsigned duration of time to a datetime.
2745///
2746/// This uses checked arithmetic and panics on overflow. To handle overflow
2747/// without panics, use [`DateTime::checked_add`].
2748impl core::ops::Add<UnsignedDuration> for DateTime {
2749 type Output = DateTime;
2750
2751 #[inline]
2752 fn add(self, rhs: UnsignedDuration) -> DateTime {
2753 self.checked_add(rhs)
2754 .expect("adding unsigned duration to datetime overflowed")
2755 }
2756}
2757
2758/// Adds an unsigned duration of time to a datetime in place.
2759///
2760/// This uses checked arithmetic and panics on overflow. To handle overflow
2761/// without panics, use [`DateTime::checked_add`].
2762impl core::ops::AddAssign<UnsignedDuration> for DateTime {
2763 #[inline]
2764 fn add_assign(&mut self, rhs: UnsignedDuration) {
2765 *self = *self + rhs
2766 }
2767}
2768
2769/// Subtracts an unsigned duration of time from a datetime.
2770///
2771/// This uses checked arithmetic and panics on overflow. To handle overflow
2772/// without panics, use [`DateTime::checked_sub`].
2773impl core::ops::Sub<UnsignedDuration> for DateTime {
2774 type Output = DateTime;
2775
2776 #[inline]
2777 fn sub(self, rhs: UnsignedDuration) -> DateTime {
2778 self.checked_sub(rhs)
2779 .expect("subtracting unsigned duration from datetime overflowed")
2780 }
2781}
2782
2783/// Subtracts an unsigned duration of time from a datetime in place.
2784///
2785/// This uses checked arithmetic and panics on overflow. To handle overflow
2786/// without panics, use [`DateTime::checked_sub`].
2787impl core::ops::SubAssign<UnsignedDuration> for DateTime {
2788 #[inline]
2789 fn sub_assign(&mut self, rhs: UnsignedDuration) {
2790 *self = *self - rhs
2791 }
2792}
2793
2794#[cfg(feature = "defmt")]
2795impl defmt::Format for DateTime {
2796 fn format(&self, f: defmt::Formatter) {
2797 use crate::fmt::{DefmtWrite, temporal::DEFAULT_DATETIME_PRINTER};
2798
2799 defmt::unwrap!(
2800 DEFAULT_DATETIME_PRINTER.print_datetime(self, DefmtWrite(f))
2801 );
2802 }
2803}
2804
2805#[cfg(feature = "serde")]
2806impl serde_core::Serialize for DateTime {
2807 #[inline]
2808 fn serialize<S: serde_core::Serializer>(
2809 &self,
2810 serializer: S,
2811 ) -> Result<S::Ok, S::Error> {
2812 serializer.collect_str(self)
2813 }
2814}
2815
2816#[cfg(feature = "serde")]
2817impl<'de> serde_core::Deserialize<'de> for DateTime {
2818 #[inline]
2819 fn deserialize<D: serde_core::Deserializer<'de>>(
2820 deserializer: D,
2821 ) -> Result<DateTime, D::Error> {
2822 use serde_core::de;
2823
2824 struct DateTimeVisitor;
2825
2826 impl<'de> de::Visitor<'de> for DateTimeVisitor {
2827 type Value = DateTime;
2828
2829 fn expecting(
2830 &self,
2831 f: &mut core::fmt::Formatter,
2832 ) -> core::fmt::Result {
2833 f.write_str("a datetime string")
2834 }
2835
2836 #[inline]
2837 fn visit_bytes<E: de::Error>(
2838 self,
2839 value: &[u8],
2840 ) -> Result<DateTime, E> {
2841 DEFAULT_DATETIME_PARSER
2842 .parse_datetime(value)
2843 .map_err(de::Error::custom)
2844 }
2845
2846 #[inline]
2847 fn visit_str<E: de::Error>(
2848 self,
2849 value: &str,
2850 ) -> Result<DateTime, E> {
2851 self.visit_bytes(value.as_bytes())
2852 }
2853 }
2854
2855 deserializer.deserialize_str(DateTimeVisitor)
2856 }
2857}
2858
2859#[cfg(test)]
2860impl quickcheck::Arbitrary for DateTime {
2861 fn arbitrary(g: &mut quickcheck::Gen) -> DateTime {
2862 let date = Date::arbitrary(g);
2863 let time = Time::arbitrary(g);
2864 DateTime::from_parts(date, time)
2865 }
2866
2867 fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = DateTime>> {
2868 alloc::boxed::Box::new(
2869 (self.date(), self.time())
2870 .shrink()
2871 .map(|(date, time)| DateTime::from_parts(date, time)),
2872 )
2873 }
2874}
2875
2876/// An iterator over periodic datetimes, created by [`DateTime::series`].
2877///
2878/// It is exhausted when the next value would exceed the limits of a [`Span`]
2879/// or [`DateTime`] value.
2880///
2881/// This iterator is created by [`DateTime::series`].
2882#[derive(Clone, Debug)]
2883pub struct DateTimeSeries {
2884 start: DateTime,
2885 period: Span,
2886 step: i64,
2887}
2888
2889impl Iterator for DateTimeSeries {
2890 type Item = DateTime;
2891
2892 #[inline]
2893 fn next(&mut self) -> Option<DateTime> {
2894 let span = self.period.checked_mul(self.step).ok()?;
2895 self.step = self.step.checked_add(1)?;
2896 let date = self.start.checked_add(span).ok()?;
2897 Some(date)
2898 }
2899}
2900
2901impl core::iter::FusedIterator for DateTimeSeries {}
2902
2903/// Options for [`DateTime::checked_add`] and [`DateTime::checked_sub`].
2904///
2905/// This type provides a way to ergonomically add one of a few different
2906/// duration types to a [`DateTime`].
2907///
2908/// The main way to construct values of this type is with its `From` trait
2909/// implementations:
2910///
2911/// * `From<Span> for DateTimeArithmetic` adds (or subtracts) the given span to
2912/// the receiver datetime.
2913/// * `From<SignedDuration> for DateTimeArithmetic` adds (or subtracts)
2914/// the given signed duration to the receiver datetime.
2915/// * `From<std::time::Duration> for DateTimeArithmetic` adds (or subtracts)
2916/// the given unsigned duration to the receiver datetime.
2917///
2918/// # Example
2919///
2920/// ```
2921/// use std::time::Duration;
2922///
2923/// use jiff::{civil::date, SignedDuration, ToSpan};
2924///
2925/// let dt = date(2024, 2, 29).at(0, 0, 0, 0);
2926/// assert_eq!(
2927/// dt.checked_add(1.year())?,
2928/// date(2025, 2, 28).at(0, 0, 0, 0),
2929/// );
2930/// assert_eq!(
2931/// dt.checked_add(SignedDuration::from_hours(24))?,
2932/// date(2024, 3, 1).at(0, 0, 0, 0),
2933/// );
2934/// assert_eq!(
2935/// dt.checked_add(Duration::from_secs(24 * 60 * 60))?,
2936/// date(2024, 3, 1).at(0, 0, 0, 0),
2937/// );
2938///
2939/// # Ok::<(), Box<dyn std::error::Error>>(())
2940/// ```
2941#[derive(Clone, Copy, Debug)]
2942pub struct DateTimeArithmetic {
2943 duration: Duration,
2944}
2945
2946impl DateTimeArithmetic {
2947 #[inline]
2948 fn checked_add(self, dt: DateTime) -> Result<DateTime, Error> {
2949 match self.duration.to_signed()? {
2950 SDuration::Span(span) => dt.checked_add_span(span),
2951 SDuration::Absolute(sdur) => dt.checked_add_duration(sdur),
2952 }
2953 }
2954
2955 #[inline]
2956 fn checked_neg(self) -> Result<DateTimeArithmetic, Error> {
2957 let duration = self.duration.checked_neg()?;
2958 Ok(DateTimeArithmetic { duration })
2959 }
2960
2961 #[inline]
2962 fn is_negative(&self) -> bool {
2963 self.duration.is_negative()
2964 }
2965}
2966
2967impl From<Span> for DateTimeArithmetic {
2968 fn from(span: Span) -> DateTimeArithmetic {
2969 let duration = Duration::from(span);
2970 DateTimeArithmetic { duration }
2971 }
2972}
2973
2974impl From<SignedDuration> for DateTimeArithmetic {
2975 fn from(sdur: SignedDuration) -> DateTimeArithmetic {
2976 let duration = Duration::from(sdur);
2977 DateTimeArithmetic { duration }
2978 }
2979}
2980
2981impl From<UnsignedDuration> for DateTimeArithmetic {
2982 fn from(udur: UnsignedDuration) -> DateTimeArithmetic {
2983 let duration = Duration::from(udur);
2984 DateTimeArithmetic { duration }
2985 }
2986}
2987
2988impl<'a> From<&'a Span> for DateTimeArithmetic {
2989 fn from(span: &'a Span) -> DateTimeArithmetic {
2990 DateTimeArithmetic::from(*span)
2991 }
2992}
2993
2994impl<'a> From<&'a SignedDuration> for DateTimeArithmetic {
2995 fn from(sdur: &'a SignedDuration) -> DateTimeArithmetic {
2996 DateTimeArithmetic::from(*sdur)
2997 }
2998}
2999
3000impl<'a> From<&'a UnsignedDuration> for DateTimeArithmetic {
3001 fn from(udur: &'a UnsignedDuration) -> DateTimeArithmetic {
3002 DateTimeArithmetic::from(*udur)
3003 }
3004}
3005
3006/// Options for [`DateTime::since`] and [`DateTime::until`].
3007///
3008/// This type provides a way to configure the calculation of
3009/// spans between two [`DateTime`] values. In particular, both
3010/// `DateTime::since` and `DateTime::until` accept anything that implements
3011/// `Into<DateTimeDifference>`. There are a few key trait implementations that
3012/// make this convenient:
3013///
3014/// * `From<DateTime> for DateTimeDifference` will construct a configuration
3015/// consisting of just the datetime. So for example, `dt1.since(dt2)` returns
3016/// the span from `dt2` to `dt1`.
3017/// * `From<Date> for DateTimeDifference` will construct a configuration
3018/// consisting of just the datetime built from the date given at midnight on
3019/// that day.
3020/// * `From<(Unit, DateTime)>` is a convenient way to specify the largest units
3021/// that should be present on the span returned. By default, the largest units
3022/// are days. Using this trait implementation is equivalent to
3023/// `DateTimeDifference::new(datetime).largest(unit)`.
3024/// * `From<(Unit, Date)>` is like the one above, but with the time component
3025/// fixed to midnight.
3026///
3027/// One can also provide a `DateTimeDifference` value directly. Doing so
3028/// is necessary to use the rounding features of calculating a span. For
3029/// example, setting the smallest unit (defaults to [`Unit::Nanosecond`]), the
3030/// rounding mode (defaults to [`RoundMode::Trunc`]) and the rounding increment
3031/// (defaults to `1`). The defaults are selected such that no rounding occurs.
3032///
3033/// Rounding a span as part of calculating it is provided as a convenience.
3034/// Callers may choose to round the span as a distinct step via
3035/// [`Span::round`], but callers may need to provide a reference date
3036/// for rounding larger units. By coupling rounding with routines like
3037/// [`DateTime::since`], the reference date can be set automatically based on
3038/// the input to `DateTime::since`.
3039///
3040/// # Example
3041///
3042/// This example shows how to round a span between two datetimes to the nearest
3043/// half-hour, with ties breaking away from zero.
3044///
3045/// ```
3046/// use jiff::{civil::{DateTime, DateTimeDifference}, RoundMode, ToSpan, Unit};
3047///
3048/// let dt1 = "2024-03-15 08:14:00.123456789".parse::<DateTime>()?;
3049/// let dt2 = "2030-03-22 15:00".parse::<DateTime>()?;
3050/// let span = dt1.until(
3051/// DateTimeDifference::new(dt2)
3052/// .smallest(Unit::Minute)
3053/// .largest(Unit::Year)
3054/// .mode(RoundMode::HalfExpand)
3055/// .increment(30),
3056/// )?;
3057/// assert_eq!(span, 6.years().days(7).hours(7).fieldwise());
3058///
3059/// # Ok::<(), Box<dyn std::error::Error>>(())
3060/// ```
3061#[derive(Clone, Copy, Debug)]
3062pub struct DateTimeDifference {
3063 datetime: DateTime,
3064 round: SpanRound<'static>,
3065}
3066
3067impl DateTimeDifference {
3068 /// Create a new default configuration for computing the span between the
3069 /// given datetime and some other datetime (specified as the receiver in
3070 /// [`DateTime::since`] or [`DateTime::until`]).
3071 #[inline]
3072 pub fn new(datetime: DateTime) -> DateTimeDifference {
3073 // We use truncation rounding by default since it seems that's
3074 // what is generally expected when computing the difference between
3075 // datetimes.
3076 //
3077 // See: https://github.com/tc39/proposal-temporal/issues/1122
3078 let round = SpanRound::new().mode(RoundMode::Trunc);
3079 DateTimeDifference { datetime, round }
3080 }
3081
3082 /// Set the smallest units allowed in the span returned.
3083 ///
3084 /// When a largest unit is not specified and the smallest unit is days
3085 /// or greater, then the largest unit is automatically set to be equal to
3086 /// the smallest unit.
3087 ///
3088 /// # Errors
3089 ///
3090 /// The smallest units must be no greater than the largest units. If this
3091 /// is violated, then computing a span with this configuration will result
3092 /// in an error.
3093 ///
3094 /// # Example
3095 ///
3096 /// This shows how to round a span between two datetimes to the nearest
3097 /// number of weeks.
3098 ///
3099 /// ```
3100 /// use jiff::{
3101 /// civil::{DateTime, DateTimeDifference},
3102 /// RoundMode, ToSpan, Unit,
3103 /// };
3104 ///
3105 /// let dt1 = "2024-03-15 08:14".parse::<DateTime>()?;
3106 /// let dt2 = "2030-11-22 08:30".parse::<DateTime>()?;
3107 /// let span = dt1.until(
3108 /// DateTimeDifference::new(dt2)
3109 /// .smallest(Unit::Week)
3110 /// .largest(Unit::Week)
3111 /// .mode(RoundMode::HalfExpand),
3112 /// )?;
3113 /// assert_eq!(span, 349.weeks().fieldwise());
3114 ///
3115 /// # Ok::<(), Box<dyn std::error::Error>>(())
3116 /// ```
3117 #[inline]
3118 pub fn smallest(self, unit: Unit) -> DateTimeDifference {
3119 DateTimeDifference { round: self.round.smallest(unit), ..self }
3120 }
3121
3122 /// Set the largest units allowed in the span returned.
3123 ///
3124 /// When a largest unit is not specified and the smallest unit is days
3125 /// or greater, then the largest unit is automatically set to be equal to
3126 /// the smallest unit. Otherwise, when the largest unit is not specified,
3127 /// it is set to days.
3128 ///
3129 /// Once a largest unit is set, there is no way to change this rounding
3130 /// configuration back to using the "automatic" default. Instead, callers
3131 /// must create a new configuration.
3132 ///
3133 /// # Errors
3134 ///
3135 /// The largest units, when set, must be at least as big as the smallest
3136 /// units (which defaults to [`Unit::Nanosecond`]). If this is violated,
3137 /// then computing a span with this configuration will result in an error.
3138 ///
3139 /// # Example
3140 ///
3141 /// This shows how to round a span between two datetimes to units no
3142 /// bigger than seconds.
3143 ///
3144 /// ```
3145 /// use jiff::{civil::{DateTime, DateTimeDifference}, ToSpan, Unit};
3146 ///
3147 /// let dt1 = "2024-03-15 08:14".parse::<DateTime>()?;
3148 /// let dt2 = "2030-11-22 08:30".parse::<DateTime>()?;
3149 /// let span = dt1.until(
3150 /// DateTimeDifference::new(dt2).largest(Unit::Second),
3151 /// )?;
3152 /// assert_eq!(span, 211076160.seconds().fieldwise());
3153 ///
3154 /// # Ok::<(), Box<dyn std::error::Error>>(())
3155 /// ```
3156 #[inline]
3157 pub fn largest(self, unit: Unit) -> DateTimeDifference {
3158 DateTimeDifference { round: self.round.largest(unit), ..self }
3159 }
3160
3161 /// Set the rounding mode.
3162 ///
3163 /// This defaults to [`RoundMode::Trunc`] since it's plausible that
3164 /// rounding "up" in the context of computing the span between
3165 /// two datetimes could be surprising in a number of cases. The
3166 /// [`RoundMode::HalfExpand`] mode corresponds to typical rounding you
3167 /// might have learned about in school. But a variety of other rounding
3168 /// modes exist.
3169 ///
3170 /// # Example
3171 ///
3172 /// This shows how to always round "up" towards positive infinity.
3173 ///
3174 /// ```
3175 /// use jiff::{
3176 /// civil::{DateTime, DateTimeDifference},
3177 /// RoundMode, ToSpan, Unit,
3178 /// };
3179 ///
3180 /// let dt1 = "2024-03-15 08:10".parse::<DateTime>()?;
3181 /// let dt2 = "2024-03-15 08:11".parse::<DateTime>()?;
3182 /// let span = dt1.until(
3183 /// DateTimeDifference::new(dt2)
3184 /// .smallest(Unit::Hour)
3185 /// .mode(RoundMode::Ceil),
3186 /// )?;
3187 /// // Only one minute elapsed, but we asked to always round up!
3188 /// assert_eq!(span, 1.hour().fieldwise());
3189 ///
3190 /// // Since `Ceil` always rounds toward positive infinity, the behavior
3191 /// // flips for a negative span.
3192 /// let span = dt1.since(
3193 /// DateTimeDifference::new(dt2)
3194 /// .smallest(Unit::Hour)
3195 /// .mode(RoundMode::Ceil),
3196 /// )?;
3197 /// assert_eq!(span, 0.hour().fieldwise());
3198 ///
3199 /// # Ok::<(), Box<dyn std::error::Error>>(())
3200 /// ```
3201 #[inline]
3202 pub fn mode(self, mode: RoundMode) -> DateTimeDifference {
3203 DateTimeDifference { round: self.round.mode(mode), ..self }
3204 }
3205
3206 /// Set the rounding increment for the smallest unit.
3207 ///
3208 /// The default value is `1`. Other values permit rounding the smallest
3209 /// unit to the nearest integer increment specified. For example, if the
3210 /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
3211 /// `30` would result in rounding in increments of a half hour. That is,
3212 /// the only minute value that could result would be `0` or `30`.
3213 ///
3214 /// # Errors
3215 ///
3216 /// When the smallest unit is less than days, the rounding increment must
3217 /// divide evenly into the next highest unit after the smallest unit
3218 /// configured (and must not be equivalent to it). For example, if the
3219 /// smallest unit is [`Unit::Nanosecond`], then *some* of the valid values
3220 /// for the rounding increment are `1`, `2`, `4`, `5`, `100` and `500`.
3221 /// Namely, any integer that divides evenly into `1,000` nanoseconds since
3222 /// there are `1,000` nanoseconds in the next highest unit (microseconds).
3223 ///
3224 /// In all cases, the increment must be greater than zero and less than
3225 /// or equal to `1_000_000_000`.
3226 ///
3227 /// The error will occur when computing the span, and not when setting
3228 /// the increment here.
3229 ///
3230 /// # Example
3231 ///
3232 /// This shows how to round the span between two datetimes to the nearest
3233 /// 5 minute increment.
3234 ///
3235 /// ```
3236 /// use jiff::{
3237 /// civil::{DateTime, DateTimeDifference},
3238 /// RoundMode, ToSpan, Unit,
3239 /// };
3240 ///
3241 /// let dt1 = "2024-03-15 08:19".parse::<DateTime>()?;
3242 /// let dt2 = "2024-03-15 12:52".parse::<DateTime>()?;
3243 /// let span = dt1.until(
3244 /// DateTimeDifference::new(dt2)
3245 /// .smallest(Unit::Minute)
3246 /// .increment(5)
3247 /// .mode(RoundMode::HalfExpand),
3248 /// )?;
3249 /// assert_eq!(span, 4.hour().minutes(35).fieldwise());
3250 ///
3251 /// # Ok::<(), Box<dyn std::error::Error>>(())
3252 /// ```
3253 #[inline]
3254 pub fn increment(self, increment: i64) -> DateTimeDifference {
3255 DateTimeDifference { round: self.round.increment(increment), ..self }
3256 }
3257
3258 /// Returns true if and only if this configuration could change the span
3259 /// via rounding.
3260 #[inline]
3261 fn rounding_may_change_span(&self) -> bool {
3262 self.round.rounding_may_change_span()
3263 }
3264
3265 /// Returns the span of time from `dt1` to the datetime in this
3266 /// configuration. The biggest units allowed are determined by the
3267 /// `smallest` and `largest` settings, but defaults to `Unit::Day`.
3268 #[inline]
3269 fn until_with_largest_unit(&self, dt1: DateTime) -> Result<Span, Error> {
3270 let dt2 = self.datetime;
3271 let largest = self
3272 .round
3273 .get_largest()
3274 .unwrap_or_else(|| self.round.get_smallest().max(Unit::Day));
3275 if largest <= Unit::Day {
3276 let diff = dt2.to_duration() - dt1.to_duration();
3277 // Note that this can fail! If largest unit is nanoseconds and the
3278 // datetimes are far enough apart, a single i64 won't be able to
3279 // represent the time difference.
3280 //
3281 // This is only true for nanoseconds. A single i64 in units of
3282 // microseconds can represent the interval between all valid
3283 // datetimes.
3284 return Span::from_invariant_duration(largest, diff);
3285 }
3286
3287 let (d1, mut d2) = (dt1.date(), dt2.date());
3288 let (t1, t2) = (dt1.time(), dt2.time());
3289 let sign = Sign::from_ordinals(d2, d1);
3290 let mut time_diff = t1.until_nanoseconds(t2);
3291 if Sign::from(time_diff) == -sign {
3292 // These unwraps will always succeed, but the argument for why is
3293 // subtle. The key here is that the only way, e.g., d2.tomorrow()
3294 // can fail is when d2 is the max date. But, if d2 is the max date,
3295 // then it's impossible for `sign < 0` since the max date is at
3296 // least as big as every other date. And thus, d2.tomorrow() is
3297 // never reached in cases where it would fail.
3298 if sign.is_positive() {
3299 d2 = d2.yesterday().unwrap();
3300 } else if sign.is_negative() {
3301 d2 = d2.tomorrow().unwrap();
3302 }
3303 time_diff += c::NANOS_PER_CIVIL_DAY * sign;
3304 }
3305 let date_span = d1.until((largest, d2))?;
3306 // Unlike in the <=Unit::Day case, this always succeeds because
3307 // every unit except for nanoseconds (which is not used here) can
3308 // represent all possible spans of time between any two civil
3309 // datetimes.
3310 let time_span = Span::from_invariant_duration(
3311 largest,
3312 SignedDuration::from_nanos(time_diff),
3313 )
3314 .expect("difference between time always fits in span");
3315 Ok(time_span
3316 .years(date_span.get_years())
3317 .months(date_span.get_months())
3318 .weeks(date_span.get_weeks())
3319 .days(date_span.get_days()))
3320 }
3321}
3322
3323impl From<DateTime> for DateTimeDifference {
3324 #[inline]
3325 fn from(dt: DateTime) -> DateTimeDifference {
3326 DateTimeDifference::new(dt)
3327 }
3328}
3329
3330impl From<Date> for DateTimeDifference {
3331 #[inline]
3332 fn from(date: Date) -> DateTimeDifference {
3333 DateTimeDifference::from(DateTime::from(date))
3334 }
3335}
3336
3337impl From<ZonedDateTime> for DateTimeDifference {
3338 #[inline]
3339 fn from(zdt: ZonedDateTime) -> DateTimeDifference {
3340 DateTimeDifference::from(DateTime::from(zdt))
3341 }
3342}
3343
3344impl<'a> From<&'a ZonedDateTime> for DateTimeDifference {
3345 #[inline]
3346 fn from(zdt: &'a ZonedDateTime) -> DateTimeDifference {
3347 DateTimeDifference::from(zdt.datetime())
3348 }
3349}
3350
3351impl From<(Unit, DateTime)> for DateTimeDifference {
3352 #[inline]
3353 fn from((largest, dt): (Unit, DateTime)) -> DateTimeDifference {
3354 DateTimeDifference::from(dt).largest(largest)
3355 }
3356}
3357
3358impl From<(Unit, Date)> for DateTimeDifference {
3359 #[inline]
3360 fn from((largest, date): (Unit, Date)) -> DateTimeDifference {
3361 DateTimeDifference::from(date).largest(largest)
3362 }
3363}
3364
3365impl From<(Unit, ZonedDateTime)> for DateTimeDifference {
3366 #[inline]
3367 fn from((largest, zdt): (Unit, ZonedDateTime)) -> DateTimeDifference {
3368 DateTimeDifference::from((largest, DateTime::from(zdt)))
3369 }
3370}
3371
3372impl<'a> From<(Unit, &'a ZonedDateTime)> for DateTimeDifference {
3373 #[inline]
3374 fn from((largest, zdt): (Unit, &'a ZonedDateTime)) -> DateTimeDifference {
3375 DateTimeDifference::from((largest, zdt.datetime()))
3376 }
3377}
3378
3379/// Options for [`DateTime::round`].
3380///
3381/// This type provides a way to configure the rounding of a civil datetime. In
3382/// particular, `DateTime::round` accepts anything that implements the
3383/// `Into<DateTimeRound>` trait. There are some trait implementations that
3384/// therefore make calling `DateTime::round` in some common cases more
3385/// ergonomic:
3386///
3387/// * `From<Unit> for DateTimeRound` will construct a rounding
3388/// configuration that rounds to the unit given. Specifically,
3389/// `DateTimeRound::new().smallest(unit)`.
3390/// * `From<(Unit, i64)> for DateTimeRound` is like the one above, but also
3391/// specifies the rounding increment for [`DateTimeRound::increment`].
3392///
3393/// Note that in the default configuration, no rounding occurs.
3394///
3395/// # Example
3396///
3397/// This example shows how to round a datetime to the nearest second:
3398///
3399/// ```
3400/// use jiff::{civil::{DateTime, date}, Unit};
3401///
3402/// let dt: DateTime = "2024-06-20 16:24:59.5".parse()?;
3403/// assert_eq!(
3404/// dt.round(Unit::Second)?,
3405/// // The second rounds up and causes minutes to increase.
3406/// date(2024, 6, 20).at(16, 25, 0, 0),
3407/// );
3408///
3409/// # Ok::<(), Box<dyn std::error::Error>>(())
3410/// ```
3411///
3412/// The above makes use of the fact that `Unit` implements
3413/// `Into<DateTimeRound>`. If you want to change the rounding mode to, say,
3414/// truncation, then you'll need to construct a `DateTimeRound` explicitly
3415/// since there are no convenience `Into` trait implementations for
3416/// [`RoundMode`].
3417///
3418/// ```
3419/// use jiff::{civil::{DateTime, DateTimeRound, date}, RoundMode, Unit};
3420///
3421/// let dt: DateTime = "2024-06-20 16:24:59.5".parse()?;
3422/// assert_eq!(
3423/// dt.round(
3424/// DateTimeRound::new().smallest(Unit::Second).mode(RoundMode::Trunc),
3425/// )?,
3426/// // The second just gets truncated as if it wasn't there.
3427/// date(2024, 6, 20).at(16, 24, 59, 0),
3428/// );
3429///
3430/// # Ok::<(), Box<dyn std::error::Error>>(())
3431/// ```
3432#[derive(Clone, Copy, Debug)]
3433pub struct DateTimeRound {
3434 smallest: Unit,
3435 mode: RoundMode,
3436 increment: i64,
3437}
3438
3439impl DateTimeRound {
3440 /// Create a new default configuration for rounding a [`DateTime`].
3441 #[inline]
3442 pub fn new() -> DateTimeRound {
3443 DateTimeRound {
3444 smallest: Unit::Nanosecond,
3445 mode: RoundMode::HalfExpand,
3446 increment: 1,
3447 }
3448 }
3449
3450 /// Set the smallest units allowed in the datetime returned after rounding.
3451 ///
3452 /// Any units below the smallest configured unit will be used, along with
3453 /// the rounding increment and rounding mode, to determine the value of the
3454 /// smallest unit. For example, when rounding `2024-06-20T03:25:30` to the
3455 /// nearest minute, the `30` second unit will result in rounding the minute
3456 /// unit of `25` up to `26` and zeroing out everything below minutes.
3457 ///
3458 /// This defaults to [`Unit::Nanosecond`].
3459 ///
3460 /// # Errors
3461 ///
3462 /// The smallest units must be no greater than [`Unit::Day`]. And when the
3463 /// smallest unit is `Unit::Day`, the rounding increment must be equal to
3464 /// `1`. Otherwise an error will be returned from [`DateTime::round`].
3465 ///
3466 /// # Example
3467 ///
3468 /// ```
3469 /// use jiff::{civil::{DateTimeRound, date}, Unit};
3470 ///
3471 /// let dt = date(2024, 6, 20).at(3, 25, 30, 0);
3472 /// assert_eq!(
3473 /// dt.round(DateTimeRound::new().smallest(Unit::Minute))?,
3474 /// date(2024, 6, 20).at(3, 26, 0, 0),
3475 /// );
3476 /// // Or, utilize the `From<Unit> for DateTimeRound` impl:
3477 /// assert_eq!(
3478 /// dt.round(Unit::Minute)?,
3479 /// date(2024, 6, 20).at(3, 26, 0, 0),
3480 /// );
3481 ///
3482 /// # Ok::<(), Box<dyn std::error::Error>>(())
3483 /// ```
3484 #[inline]
3485 pub fn smallest(self, unit: Unit) -> DateTimeRound {
3486 DateTimeRound { smallest: unit, ..self }
3487 }
3488
3489 /// Set the rounding mode.
3490 ///
3491 /// This defaults to [`RoundMode::HalfExpand`], which rounds away from
3492 /// zero. It matches the kind of rounding you might have been taught in
3493 /// school.
3494 ///
3495 /// # Example
3496 ///
3497 /// This shows how to always round datetimes up towards positive infinity.
3498 ///
3499 /// ```
3500 /// use jiff::{civil::{DateTime, DateTimeRound, date}, RoundMode, Unit};
3501 ///
3502 /// let dt: DateTime = "2024-06-20 03:25:01".parse()?;
3503 /// assert_eq!(
3504 /// dt.round(
3505 /// DateTimeRound::new()
3506 /// .smallest(Unit::Minute)
3507 /// .mode(RoundMode::Ceil),
3508 /// )?,
3509 /// date(2024, 6, 20).at(3, 26, 0, 0),
3510 /// );
3511 ///
3512 /// # Ok::<(), Box<dyn std::error::Error>>(())
3513 /// ```
3514 #[inline]
3515 pub fn mode(self, mode: RoundMode) -> DateTimeRound {
3516 DateTimeRound { mode, ..self }
3517 }
3518
3519 /// Set the rounding increment for the smallest unit.
3520 ///
3521 /// The default value is `1`. Other values permit rounding the smallest
3522 /// unit to the nearest integer increment specified. For example, if the
3523 /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
3524 /// `30` would result in rounding in increments of a half hour. That is,
3525 /// the only minute value that could result would be `0` or `30`.
3526 ///
3527 /// # Errors
3528 ///
3529 /// When the smallest unit is `Unit::Day`, then the rounding increment must
3530 /// be `1` or else [`DateTime::round`] will return an error.
3531 ///
3532 /// For other units, the rounding increment must divide evenly into the
3533 /// next highest unit above the smallest unit set. The rounding increment
3534 /// must also not be equal to the next highest unit. For example, if the
3535 /// smallest unit is [`Unit::Nanosecond`], then *some* of the valid values
3536 /// for the rounding increment are `1`, `2`, `4`, `5`, `100` and `500`.
3537 /// Namely, any integer that divides evenly into `1,000` nanoseconds since
3538 /// there are `1,000` nanoseconds in the next highest unit (microseconds).
3539 ///
3540 /// In all cases, the increment must be greater than zero and less than or
3541 /// equal to `1_000_000_000`.
3542 ///
3543 /// # Example
3544 ///
3545 /// This example shows how to round a datetime to the nearest 10 minute
3546 /// increment.
3547 ///
3548 /// ```
3549 /// use jiff::{civil::{DateTime, DateTimeRound, date}, RoundMode, Unit};
3550 ///
3551 /// let dt: DateTime = "2024-06-20 03:24:59".parse()?;
3552 /// assert_eq!(
3553 /// dt.round((Unit::Minute, 10))?,
3554 /// date(2024, 6, 20).at(3, 20, 0, 0),
3555 /// );
3556 ///
3557 /// # Ok::<(), Box<dyn std::error::Error>>(())
3558 /// ```
3559 #[inline]
3560 pub fn increment(self, increment: i64) -> DateTimeRound {
3561 DateTimeRound { increment, ..self }
3562 }
3563
3564 /// Does the actual rounding.
3565 ///
3566 /// A non-public configuration here is the length of a day. For civil
3567 /// datetimes, this should always be `NANOS_PER_CIVIL_DAY`. But this
3568 /// rounding routine is also used for `ZonedDateTime` rounding, and in that
3569 /// context, the length of a day can vary based on the time zone.
3570 pub(crate) fn round(&self, dt: DateTime) -> Result<DateTime, Error> {
3571 // ref: https://tc39.es/proposal-temporal/#sec-temporal.plaindatetime.prototype.round
3572
3573 // We don't do any rounding in this case and there are no possible
3574 // error conditions under this configuration. So just bail.
3575 if self.smallest == Unit::Nanosecond && self.increment == 1 {
3576 return Ok(dt);
3577 }
3578
3579 let increment =
3580 Increment::for_datetime(self.smallest, self.increment)?;
3581 let time_nanos = dt.time().to_duration();
3582 let sign = Sign::from(dt.date().year());
3583 let time_rounded = increment.round(self.mode, time_nanos)?;
3584 let (days, time_nanos) = time_rounded.as_civil_days_with_remainder();
3585 // OK because `abs(days)` here can never be greater than 1. Namely,
3586 // rounding time increments are limited to values that divide evenly
3587 // into the corresponding maximal value. And a `day` increment is
3588 // limited to `1`. So even starting with the maximal `dt.time()` value
3589 // (the last nanosecond in a civil day), we can never round past 1 day.
3590 let days = sign * days;
3591 // OK because `time_nanos` is guaranteed to be less than a single full
3592 // civil day.
3593 let time = Time::from_duration(time_nanos).unwrap();
3594
3595 // OK because `abs(days) <= 1` (see above comment) and
3596 // `dt.date().day()` can never exceed `31`. So the result always fits
3597 // into an `i64`.
3598 let days_len = (i64::from(dt.date().day()) - 1) + days;
3599 let start = dt.date().first_of_month();
3600 // `abs(days)` is always <= 1, and so `days_len` should
3601 // always be at most 1 greater (or less) than where we started. If we
3602 // started at, e.g., `DateTime::MAX`, then this could overflow.
3603 let date = start
3604 .checked_add(Span::new().days(days_len))
3605 .context(E::FailedAddDays)?;
3606 Ok(DateTime::from_parts(date, time))
3607 }
3608
3609 pub(crate) fn get_smallest(&self) -> Unit {
3610 self.smallest
3611 }
3612
3613 pub(crate) fn get_mode(&self) -> RoundMode {
3614 self.mode
3615 }
3616
3617 pub(crate) fn get_increment(&self) -> i64 {
3618 self.increment
3619 }
3620}
3621
3622impl Default for DateTimeRound {
3623 #[inline]
3624 fn default() -> DateTimeRound {
3625 DateTimeRound::new()
3626 }
3627}
3628
3629impl From<Unit> for DateTimeRound {
3630 #[inline]
3631 fn from(unit: Unit) -> DateTimeRound {
3632 DateTimeRound::default().smallest(unit)
3633 }
3634}
3635
3636impl From<(Unit, i64)> for DateTimeRound {
3637 #[inline]
3638 fn from((unit, increment): (Unit, i64)) -> DateTimeRound {
3639 DateTimeRound::from(unit).increment(increment)
3640 }
3641}
3642
3643/// A builder for setting the fields on a [`DateTime`].
3644///
3645/// This builder is constructed via [`DateTime::with`].
3646///
3647/// # Example
3648///
3649/// The builder ensures one can chain together the individual components of a
3650/// datetime without it failing at an intermediate step. For example, if you
3651/// had a date of `2024-10-31T00:00:00` and wanted to change both the day and
3652/// the month, and each setting was validated independent of the other, you
3653/// would need to be careful to set the day first and then the month. In some
3654/// cases, you would need to set the month first and then the day!
3655///
3656/// But with the builder, you can set values in any order:
3657///
3658/// ```
3659/// use jiff::civil::date;
3660///
3661/// let dt1 = date(2024, 10, 31).at(0, 0, 0, 0);
3662/// let dt2 = dt1.with().month(11).day(30).build()?;
3663/// assert_eq!(dt2, date(2024, 11, 30).at(0, 0, 0, 0));
3664///
3665/// let dt1 = date(2024, 4, 30).at(0, 0, 0, 0);
3666/// let dt2 = dt1.with().day(31).month(7).build()?;
3667/// assert_eq!(dt2, date(2024, 7, 31).at(0, 0, 0, 0));
3668///
3669/// # Ok::<(), Box<dyn std::error::Error>>(())
3670/// ```
3671#[derive(Clone, Copy, Debug)]
3672pub struct DateTimeWith {
3673 date_with: DateWith,
3674 time_with: TimeWith,
3675}
3676
3677impl DateTimeWith {
3678 #[inline]
3679 fn new(original: DateTime) -> DateTimeWith {
3680 DateTimeWith {
3681 date_with: original.date().with(),
3682 time_with: original.time().with(),
3683 }
3684 }
3685
3686 /// Create a new `DateTime` from the fields set on this configuration.
3687 ///
3688 /// An error occurs when the fields combine to an invalid datetime.
3689 ///
3690 /// For any fields not set on this configuration, the values are taken from
3691 /// the [`DateTime`] that originally created this configuration. When no
3692 /// values are set, this routine is guaranteed to succeed and will always
3693 /// return the original datetime without modification.
3694 ///
3695 /// # Example
3696 ///
3697 /// This creates a datetime corresponding to the last day in the year at
3698 /// noon:
3699 ///
3700 /// ```
3701 /// use jiff::civil::date;
3702 ///
3703 /// let dt = date(2023, 1, 1).at(12, 0, 0, 0);
3704 /// assert_eq!(
3705 /// dt.with().day_of_year_no_leap(365).build()?,
3706 /// date(2023, 12, 31).at(12, 0, 0, 0),
3707 /// );
3708 ///
3709 /// // It also works with leap years for the same input:
3710 /// let dt = date(2024, 1, 1).at(12, 0, 0, 0);
3711 /// assert_eq!(
3712 /// dt.with().day_of_year_no_leap(365).build()?,
3713 /// date(2024, 12, 31).at(12, 0, 0, 0),
3714 /// );
3715 ///
3716 /// # Ok::<(), Box<dyn std::error::Error>>(())
3717 /// ```
3718 ///
3719 /// # Example: error for invalid datetime
3720 ///
3721 /// If the fields combine to form an invalid date, then an error is
3722 /// returned:
3723 ///
3724 /// ```
3725 /// use jiff::civil::date;
3726 ///
3727 /// let dt = date(2024, 11, 30).at(15, 30, 0, 0);
3728 /// assert!(dt.with().day(31).build().is_err());
3729 ///
3730 /// let dt = date(2024, 2, 29).at(15, 30, 0, 0);
3731 /// assert!(dt.with().year(2023).build().is_err());
3732 /// ```
3733 #[inline]
3734 pub fn build(self) -> Result<DateTime, Error> {
3735 let date = self.date_with.build()?;
3736 let time = self.time_with.build()?;
3737 Ok(DateTime::from_parts(date, time))
3738 }
3739
3740 /// Set the year, month and day fields via the `Date` given.
3741 ///
3742 /// This overrides any previous year, month or day settings.
3743 ///
3744 /// # Example
3745 ///
3746 /// This shows how to create a new datetime with a different date:
3747 ///
3748 /// ```
3749 /// use jiff::civil::date;
3750 ///
3751 /// let dt1 = date(2005, 11, 5).at(15, 30, 0, 0);
3752 /// let dt2 = dt1.with().date(date(2017, 10, 31)).build()?;
3753 /// // The date changes but the time remains the same.
3754 /// assert_eq!(dt2, date(2017, 10, 31).at(15, 30, 0, 0));
3755 ///
3756 /// # Ok::<(), Box<dyn std::error::Error>>(())
3757 /// ```
3758 #[inline]
3759 pub fn date(self, date: Date) -> DateTimeWith {
3760 DateTimeWith { date_with: date.with(), ..self }
3761 }
3762
3763 /// Set the hour, minute, second, millisecond, microsecond and nanosecond
3764 /// fields via the `Time` given.
3765 ///
3766 /// This overrides any previous hour, minute, second, millisecond,
3767 /// microsecond, nanosecond or subsecond nanosecond settings.
3768 ///
3769 /// # Example
3770 ///
3771 /// This shows how to create a new datetime with a different time:
3772 ///
3773 /// ```
3774 /// use jiff::civil::{date, time};
3775 ///
3776 /// let dt1 = date(2005, 11, 5).at(15, 30, 0, 0);
3777 /// let dt2 = dt1.with().time(time(23, 59, 59, 123_456_789)).build()?;
3778 /// // The time changes but the date remains the same.
3779 /// assert_eq!(dt2, date(2005, 11, 5).at(23, 59, 59, 123_456_789));
3780 ///
3781 /// # Ok::<(), Box<dyn std::error::Error>>(())
3782 /// ```
3783 #[inline]
3784 pub fn time(self, time: Time) -> DateTimeWith {
3785 DateTimeWith { time_with: time.with(), ..self }
3786 }
3787
3788 /// Set the year field on a [`DateTime`].
3789 ///
3790 /// One can access this value via [`DateTime::year`].
3791 ///
3792 /// This overrides any previous year settings.
3793 ///
3794 /// # Errors
3795 ///
3796 /// This returns an error when [`DateTimeWith::build`] is called if the
3797 /// given year is outside the range `-9999..=9999`. This can also return an
3798 /// error if the resulting date is otherwise invalid.
3799 ///
3800 /// # Example
3801 ///
3802 /// This shows how to create a new datetime with a different year:
3803 ///
3804 /// ```
3805 /// use jiff::civil::date;
3806 ///
3807 /// let dt1 = date(2005, 11, 5).at(15, 30, 0, 0);
3808 /// assert_eq!(dt1.year(), 2005);
3809 /// let dt2 = dt1.with().year(2007).build()?;
3810 /// assert_eq!(dt2.year(), 2007);
3811 ///
3812 /// # Ok::<(), Box<dyn std::error::Error>>(())
3813 /// ```
3814 ///
3815 /// # Example: only changing the year can fail
3816 ///
3817 /// For example, while `2024-02-29T01:30:00` is valid,
3818 /// `2023-02-29T01:30:00` is not:
3819 ///
3820 /// ```
3821 /// use jiff::civil::date;
3822 ///
3823 /// let dt = date(2024, 2, 29).at(1, 30, 0, 0);
3824 /// assert!(dt.with().year(2023).build().is_err());
3825 /// ```
3826 #[inline]
3827 pub fn year(self, year: i16) -> DateTimeWith {
3828 DateTimeWith { date_with: self.date_with.year(year), ..self }
3829 }
3830
3831 /// Set year of a datetime via its era and its non-negative numeric
3832 /// component.
3833 ///
3834 /// One can access this value via [`DateTime::era_year`].
3835 ///
3836 /// # Errors
3837 ///
3838 /// This returns an error when [`DateTimeWith::build`] is called if the
3839 /// year is outside the range for the era specified. For [`Era::BCE`], the
3840 /// range is `1..=10000`. For [`Era::CE`], the range is `1..=9999`.
3841 ///
3842 /// # Example
3843 ///
3844 /// This shows that `CE` years are equivalent to the years used by this
3845 /// crate:
3846 ///
3847 /// ```
3848 /// use jiff::civil::{Era, date};
3849 ///
3850 /// let dt1 = date(2005, 11, 5).at(8, 0, 0, 0);
3851 /// assert_eq!(dt1.year(), 2005);
3852 /// let dt2 = dt1.with().era_year(2007, Era::CE).build()?;
3853 /// assert_eq!(dt2.year(), 2007);
3854 ///
3855 /// // CE years are always positive and can be at most 9999:
3856 /// assert!(dt1.with().era_year(-5, Era::CE).build().is_err());
3857 /// assert!(dt1.with().era_year(10_000, Era::CE).build().is_err());
3858 ///
3859 /// # Ok::<(), Box<dyn std::error::Error>>(())
3860 /// ```
3861 ///
3862 /// But `BCE` years always correspond to years less than or equal to `0`
3863 /// in this crate:
3864 ///
3865 /// ```
3866 /// use jiff::civil::{Era, date};
3867 ///
3868 /// let dt1 = date(-27, 7, 1).at(8, 22, 30, 0);
3869 /// assert_eq!(dt1.year(), -27);
3870 /// assert_eq!(dt1.era_year(), (28, Era::BCE));
3871 ///
3872 /// let dt2 = dt1.with().era_year(509, Era::BCE).build()?;
3873 /// assert_eq!(dt2.year(), -508);
3874 /// assert_eq!(dt2.era_year(), (509, Era::BCE));
3875 ///
3876 /// let dt2 = dt1.with().era_year(10_000, Era::BCE).build()?;
3877 /// assert_eq!(dt2.year(), -9_999);
3878 /// assert_eq!(dt2.era_year(), (10_000, Era::BCE));
3879 ///
3880 /// // BCE years are always positive and can be at most 10000:
3881 /// assert!(dt1.with().era_year(-5, Era::BCE).build().is_err());
3882 /// assert!(dt1.with().era_year(10_001, Era::BCE).build().is_err());
3883 ///
3884 /// # Ok::<(), Box<dyn std::error::Error>>(())
3885 /// ```
3886 ///
3887 /// # Example: overrides `DateTimeWith::year`
3888 ///
3889 /// Setting this option will override any previous `DateTimeWith::year`
3890 /// option:
3891 ///
3892 /// ```
3893 /// use jiff::civil::{Era, date};
3894 ///
3895 /// let dt1 = date(2024, 7, 2).at(10, 27, 10, 123);
3896 /// let dt2 = dt1.with().year(2000).era_year(1900, Era::CE).build()?;
3897 /// assert_eq!(dt2, date(1900, 7, 2).at(10, 27, 10, 123));
3898 ///
3899 /// # Ok::<(), Box<dyn std::error::Error>>(())
3900 /// ```
3901 ///
3902 /// Similarly, `DateTimeWith::year` will override any previous call to
3903 /// `DateTimeWith::era_year`:
3904 ///
3905 /// ```
3906 /// use jiff::civil::{Era, date};
3907 ///
3908 /// let dt1 = date(2024, 7, 2).at(19, 0, 1, 1);
3909 /// let dt2 = dt1.with().era_year(1900, Era::CE).year(2000).build()?;
3910 /// assert_eq!(dt2, date(2000, 7, 2).at(19, 0, 1, 1));
3911 ///
3912 /// # Ok::<(), Box<dyn std::error::Error>>(())
3913 /// ```
3914 #[inline]
3915 pub fn era_year(self, year: i16, era: Era) -> DateTimeWith {
3916 DateTimeWith { date_with: self.date_with.era_year(year, era), ..self }
3917 }
3918
3919 /// Set the month field on a [`DateTime`].
3920 ///
3921 /// One can access this value via [`DateTime::month`].
3922 ///
3923 /// This overrides any previous month settings.
3924 ///
3925 /// # Errors
3926 ///
3927 /// This returns an error when [`DateTimeWith::build`] is called if the
3928 /// given month is outside the range `1..=12`. This can also return an
3929 /// error if the resulting date is otherwise invalid.
3930 ///
3931 /// # Example
3932 ///
3933 /// This shows how to create a new datetime with a different month:
3934 ///
3935 /// ```
3936 /// use jiff::civil::date;
3937 ///
3938 /// let dt1 = date(2005, 11, 5).at(18, 3, 59, 123_456_789);
3939 /// assert_eq!(dt1.month(), 11);
3940 /// let dt2 = dt1.with().month(6).build()?;
3941 /// assert_eq!(dt2.month(), 6);
3942 ///
3943 /// # Ok::<(), Box<dyn std::error::Error>>(())
3944 /// ```
3945 ///
3946 /// # Example: only changing the month can fail
3947 ///
3948 /// For example, while `2024-10-31T00:00:00` is valid,
3949 /// `2024-11-31T00:00:00` is not:
3950 ///
3951 /// ```
3952 /// use jiff::civil::date;
3953 ///
3954 /// let dt = date(2024, 10, 31).at(0, 0, 0, 0);
3955 /// assert!(dt.with().month(11).build().is_err());
3956 /// ```
3957 #[inline]
3958 pub fn month(self, month: i8) -> DateTimeWith {
3959 DateTimeWith { date_with: self.date_with.month(month), ..self }
3960 }
3961
3962 /// Set the day field on a [`DateTime`].
3963 ///
3964 /// One can access this value via [`DateTime::day`].
3965 ///
3966 /// This overrides any previous day settings.
3967 ///
3968 /// # Errors
3969 ///
3970 /// This returns an error when [`DateTimeWith::build`] is called if the
3971 /// given given day is outside of allowable days for the corresponding year
3972 /// and month fields.
3973 ///
3974 /// # Example
3975 ///
3976 /// This shows some examples of setting the day, including a leap day:
3977 ///
3978 /// ```
3979 /// use jiff::civil::date;
3980 ///
3981 /// let dt1 = date(2024, 2, 5).at(21, 59, 1, 999);
3982 /// assert_eq!(dt1.day(), 5);
3983 /// let dt2 = dt1.with().day(10).build()?;
3984 /// assert_eq!(dt2.day(), 10);
3985 /// let dt3 = dt1.with().day(29).build()?;
3986 /// assert_eq!(dt3.day(), 29);
3987 ///
3988 /// # Ok::<(), Box<dyn std::error::Error>>(())
3989 /// ```
3990 ///
3991 /// # Example: changing only the day can fail
3992 ///
3993 /// This shows some examples that will fail:
3994 ///
3995 /// ```
3996 /// use jiff::civil::date;
3997 ///
3998 /// let dt1 = date(2023, 2, 5).at(22, 58, 58, 9_999);
3999 /// // 2023 is not a leap year
4000 /// assert!(dt1.with().day(29).build().is_err());
4001 ///
4002 /// // September has 30 days, not 31.
4003 /// let dt1 = date(2023, 9, 5).at(22, 58, 58, 9_999);
4004 /// assert!(dt1.with().day(31).build().is_err());
4005 /// ```
4006 #[inline]
4007 pub fn day(self, day: i8) -> DateTimeWith {
4008 DateTimeWith { date_with: self.date_with.day(day), ..self }
4009 }
4010
4011 /// Set the day field on a [`DateTime`] via the ordinal number of a day
4012 /// within a year.
4013 ///
4014 /// When used, any settings for month are ignored since the month is
4015 /// determined by the day of the year.
4016 ///
4017 /// The valid values for `day` are `1..=366`. Note though that `366` is
4018 /// only valid for leap years.
4019 ///
4020 /// This overrides any previous day settings.
4021 ///
4022 /// # Errors
4023 ///
4024 /// This returns an error when [`DateTimeWith::build`] is called if the
4025 /// given day is outside the allowed range of `1..=366`, or when a value of
4026 /// `366` is given for a non-leap year.
4027 ///
4028 /// # Example
4029 ///
4030 /// This demonstrates that if a year is a leap year, then `60` corresponds
4031 /// to February 29:
4032 ///
4033 /// ```
4034 /// use jiff::civil::date;
4035 ///
4036 /// let dt = date(2024, 1, 1).at(23, 59, 59, 999_999_999);
4037 /// assert_eq!(
4038 /// dt.with().day_of_year(60).build()?,
4039 /// date(2024, 2, 29).at(23, 59, 59, 999_999_999),
4040 /// );
4041 ///
4042 /// # Ok::<(), Box<dyn std::error::Error>>(())
4043 /// ```
4044 ///
4045 /// But for non-leap years, day 60 is March 1:
4046 ///
4047 /// ```
4048 /// use jiff::civil::date;
4049 ///
4050 /// let dt = date(2023, 1, 1).at(23, 59, 59, 999_999_999);
4051 /// assert_eq!(
4052 /// dt.with().day_of_year(60).build()?,
4053 /// date(2023, 3, 1).at(23, 59, 59, 999_999_999),
4054 /// );
4055 ///
4056 /// # Ok::<(), Box<dyn std::error::Error>>(())
4057 /// ```
4058 ///
4059 /// And using `366` for a non-leap year will result in an error, since
4060 /// non-leap years only have 365 days:
4061 ///
4062 /// ```
4063 /// use jiff::civil::date;
4064 ///
4065 /// let dt = date(2023, 1, 1).at(0, 0, 0, 0);
4066 /// assert!(dt.with().day_of_year(366).build().is_err());
4067 /// // The maximal year is not a leap year, so it returns an error too.
4068 /// let dt = date(9999, 1, 1).at(0, 0, 0, 0);
4069 /// assert!(dt.with().day_of_year(366).build().is_err());
4070 /// ```
4071 #[inline]
4072 pub fn day_of_year(self, day: i16) -> DateTimeWith {
4073 DateTimeWith { date_with: self.date_with.day_of_year(day), ..self }
4074 }
4075
4076 /// Set the day field on a [`DateTime`] via the ordinal number of a day
4077 /// within a year, but ignoring leap years.
4078 ///
4079 /// When used, any settings for month are ignored since the month is
4080 /// determined by the day of the year.
4081 ///
4082 /// The valid values for `day` are `1..=365`. The value `365` always
4083 /// corresponds to the last day of the year, even for leap years. It is
4084 /// impossible for this routine to return a datetime corresponding to
4085 /// February 29.
4086 ///
4087 /// This overrides any previous day settings.
4088 ///
4089 /// # Errors
4090 ///
4091 /// This returns an error when [`DateTimeWith::build`] is called if the
4092 /// given day is outside the allowed range of `1..=365`.
4093 ///
4094 /// # Example
4095 ///
4096 /// This demonstrates that `60` corresponds to March 1, regardless of
4097 /// whether the year is a leap year or not:
4098 ///
4099 /// ```
4100 /// use jiff::civil::date;
4101 ///
4102 /// let dt = date(2023, 1, 1).at(23, 59, 59, 999_999_999);
4103 /// assert_eq!(
4104 /// dt.with().day_of_year_no_leap(60).build()?,
4105 /// date(2023, 3, 1).at(23, 59, 59, 999_999_999),
4106 /// );
4107 ///
4108 /// let dt = date(2024, 1, 1).at(23, 59, 59, 999_999_999);
4109 /// assert_eq!(
4110 /// dt.with().day_of_year_no_leap(60).build()?,
4111 /// date(2024, 3, 1).at(23, 59, 59, 999_999_999),
4112 /// );
4113 ///
4114 /// # Ok::<(), Box<dyn std::error::Error>>(())
4115 /// ```
4116 ///
4117 /// And using `365` for any year will always yield the last day of the
4118 /// year:
4119 ///
4120 /// ```
4121 /// use jiff::civil::date;
4122 ///
4123 /// let dt = date(2023, 1, 1).at(23, 59, 59, 999_999_999);
4124 /// assert_eq!(
4125 /// dt.with().day_of_year_no_leap(365).build()?,
4126 /// dt.last_of_year(),
4127 /// );
4128 ///
4129 /// let dt = date(2024, 1, 1).at(23, 59, 59, 999_999_999);
4130 /// assert_eq!(
4131 /// dt.with().day_of_year_no_leap(365).build()?,
4132 /// dt.last_of_year(),
4133 /// );
4134 ///
4135 /// let dt = date(9999, 1, 1).at(23, 59, 59, 999_999_999);
4136 /// assert_eq!(
4137 /// dt.with().day_of_year_no_leap(365).build()?,
4138 /// dt.last_of_year(),
4139 /// );
4140 ///
4141 /// # Ok::<(), Box<dyn std::error::Error>>(())
4142 /// ```
4143 ///
4144 /// A value of `366` is out of bounds, even for leap years:
4145 ///
4146 /// ```
4147 /// use jiff::civil::date;
4148 ///
4149 /// let dt = date(2024, 1, 1).at(5, 30, 0, 0);
4150 /// assert!(dt.with().day_of_year_no_leap(366).build().is_err());
4151 /// ```
4152 #[inline]
4153 pub fn day_of_year_no_leap(self, day: i16) -> DateTimeWith {
4154 DateTimeWith {
4155 date_with: self.date_with.day_of_year_no_leap(day),
4156 ..self
4157 }
4158 }
4159
4160 /// Set the hour field on a [`DateTime`].
4161 ///
4162 /// One can access this value via [`DateTime::hour`].
4163 ///
4164 /// This overrides any previous hour settings.
4165 ///
4166 /// # Errors
4167 ///
4168 /// This returns an error when [`DateTimeWith::build`] is called if the
4169 /// given hour is outside the range `0..=23`.
4170 ///
4171 /// # Example
4172 ///
4173 /// ```
4174 /// use jiff::civil::time;
4175 ///
4176 /// let dt1 = time(15, 21, 59, 0).on(2010, 6, 1);
4177 /// assert_eq!(dt1.hour(), 15);
4178 /// let dt2 = dt1.with().hour(3).build()?;
4179 /// assert_eq!(dt2.hour(), 3);
4180 ///
4181 /// # Ok::<(), Box<dyn std::error::Error>>(())
4182 /// ```
4183 #[inline]
4184 pub fn hour(self, hour: i8) -> DateTimeWith {
4185 DateTimeWith { time_with: self.time_with.hour(hour), ..self }
4186 }
4187
4188 /// Set the minute field on a [`DateTime`].
4189 ///
4190 /// One can access this value via [`DateTime::minute`].
4191 ///
4192 /// This overrides any previous minute settings.
4193 ///
4194 /// # Errors
4195 ///
4196 /// This returns an error when [`DateTimeWith::build`] is called if the
4197 /// given minute is outside the range `0..=59`.
4198 ///
4199 /// # Example
4200 ///
4201 /// ```
4202 /// use jiff::civil::time;
4203 ///
4204 /// let dt1 = time(15, 21, 59, 0).on(2010, 6, 1);
4205 /// assert_eq!(dt1.minute(), 21);
4206 /// let dt2 = dt1.with().minute(3).build()?;
4207 /// assert_eq!(dt2.minute(), 3);
4208 ///
4209 /// # Ok::<(), Box<dyn std::error::Error>>(())
4210 /// ```
4211 #[inline]
4212 pub fn minute(self, minute: i8) -> DateTimeWith {
4213 DateTimeWith { time_with: self.time_with.minute(minute), ..self }
4214 }
4215
4216 /// Set the second field on a [`DateTime`].
4217 ///
4218 /// One can access this value via [`DateTime::second`].
4219 ///
4220 /// This overrides any previous second settings.
4221 ///
4222 /// # Errors
4223 ///
4224 /// This returns an error when [`DateTimeWith::build`] is called if the
4225 /// given second is outside the range `0..=59`.
4226 ///
4227 /// # Example
4228 ///
4229 /// ```
4230 /// use jiff::civil::time;
4231 ///
4232 /// let dt1 = time(15, 21, 59, 0).on(2010, 6, 1);
4233 /// assert_eq!(dt1.second(), 59);
4234 /// let dt2 = dt1.with().second(3).build()?;
4235 /// assert_eq!(dt2.second(), 3);
4236 ///
4237 /// # Ok::<(), Box<dyn std::error::Error>>(())
4238 /// ```
4239 #[inline]
4240 pub fn second(self, second: i8) -> DateTimeWith {
4241 DateTimeWith { time_with: self.time_with.second(second), ..self }
4242 }
4243
4244 /// Set the millisecond field on a [`DateTime`].
4245 ///
4246 /// One can access this value via [`DateTime::millisecond`].
4247 ///
4248 /// This overrides any previous millisecond settings.
4249 ///
4250 /// Note that this only sets the millisecond component. It does
4251 /// not change the microsecond or nanosecond components. To set
4252 /// the fractional second component to nanosecond precision, use
4253 /// [`DateTimeWith::subsec_nanosecond`].
4254 ///
4255 /// # Errors
4256 ///
4257 /// This returns an error when [`DateTimeWith::build`] is called if the
4258 /// given millisecond is outside the range `0..=999`, or if both this and
4259 /// [`DateTimeWith::subsec_nanosecond`] are set.
4260 ///
4261 /// # Example
4262 ///
4263 /// This shows the relationship between [`DateTime::millisecond`] and
4264 /// [`DateTime::subsec_nanosecond`]:
4265 ///
4266 /// ```
4267 /// use jiff::civil::time;
4268 ///
4269 /// let dt1 = time(15, 21, 35, 0).on(2010, 6, 1);
4270 /// let dt2 = dt1.with().millisecond(123).build()?;
4271 /// assert_eq!(dt2.subsec_nanosecond(), 123_000_000);
4272 ///
4273 /// # Ok::<(), Box<dyn std::error::Error>>(())
4274 /// ```
4275 #[inline]
4276 pub fn millisecond(self, millisecond: i16) -> DateTimeWith {
4277 DateTimeWith {
4278 time_with: self.time_with.millisecond(millisecond),
4279 ..self
4280 }
4281 }
4282
4283 /// Set the microsecond field on a [`DateTime`].
4284 ///
4285 /// One can access this value via [`DateTime::microsecond`].
4286 ///
4287 /// This overrides any previous microsecond settings.
4288 ///
4289 /// Note that this only sets the microsecond component. It does
4290 /// not change the millisecond or nanosecond components. To set
4291 /// the fractional second component to nanosecond precision, use
4292 /// [`DateTimeWith::subsec_nanosecond`].
4293 ///
4294 /// # Errors
4295 ///
4296 /// This returns an error when [`DateTimeWith::build`] is called if the
4297 /// given microsecond is outside the range `0..=999`, or if both this and
4298 /// [`DateTimeWith::subsec_nanosecond`] are set.
4299 ///
4300 /// # Example
4301 ///
4302 /// This shows the relationship between [`DateTime::microsecond`] and
4303 /// [`DateTime::subsec_nanosecond`]:
4304 ///
4305 /// ```
4306 /// use jiff::civil::time;
4307 ///
4308 /// let dt1 = time(15, 21, 35, 0).on(2010, 6, 1);
4309 /// let dt2 = dt1.with().microsecond(123).build()?;
4310 /// assert_eq!(dt2.subsec_nanosecond(), 123_000);
4311 ///
4312 /// # Ok::<(), Box<dyn std::error::Error>>(())
4313 /// ```
4314 #[inline]
4315 pub fn microsecond(self, microsecond: i16) -> DateTimeWith {
4316 DateTimeWith {
4317 time_with: self.time_with.microsecond(microsecond),
4318 ..self
4319 }
4320 }
4321
4322 /// Set the nanosecond field on a [`DateTime`].
4323 ///
4324 /// One can access this value via [`DateTime::nanosecond`].
4325 ///
4326 /// This overrides any previous nanosecond settings.
4327 ///
4328 /// Note that this only sets the nanosecond component. It does
4329 /// not change the millisecond or microsecond components. To set
4330 /// the fractional second component to nanosecond precision, use
4331 /// [`DateTimeWith::subsec_nanosecond`].
4332 ///
4333 /// # Errors
4334 ///
4335 /// This returns an error when [`DateTimeWith::build`] is called if the
4336 /// given nanosecond is outside the range `0..=999`, or if both this and
4337 /// [`DateTimeWith::subsec_nanosecond`] are set.
4338 ///
4339 /// # Example
4340 ///
4341 /// This shows the relationship between [`DateTime::nanosecond`] and
4342 /// [`DateTime::subsec_nanosecond`]:
4343 ///
4344 /// ```
4345 /// use jiff::civil::time;
4346 ///
4347 /// let dt1 = time(15, 21, 35, 0).on(2010, 6, 1);
4348 /// let dt2 = dt1.with().nanosecond(123).build()?;
4349 /// assert_eq!(dt2.subsec_nanosecond(), 123);
4350 ///
4351 /// # Ok::<(), Box<dyn std::error::Error>>(())
4352 /// ```
4353 #[inline]
4354 pub fn nanosecond(self, nanosecond: i16) -> DateTimeWith {
4355 DateTimeWith {
4356 time_with: self.time_with.nanosecond(nanosecond),
4357 ..self
4358 }
4359 }
4360
4361 /// Set the subsecond nanosecond field on a [`DateTime`].
4362 ///
4363 /// If you want to access this value on `DateTime`, then use
4364 /// [`DateTime::subsec_nanosecond`].
4365 ///
4366 /// This overrides any previous subsecond nanosecond settings.
4367 ///
4368 /// Note that this sets the entire fractional second component to
4369 /// nanosecond precision, and overrides any individual millisecond,
4370 /// microsecond or nanosecond settings. To set individual components,
4371 /// use [`DateTimeWith::millisecond`], [`DateTimeWith::microsecond`] or
4372 /// [`DateTimeWith::nanosecond`].
4373 ///
4374 /// # Errors
4375 ///
4376 /// This returns an error when [`DateTimeWith::build`] is called if the
4377 /// given subsecond nanosecond is outside the range `0..=999,999,999`,
4378 /// or if both this and one of [`DateTimeWith::millisecond`],
4379 /// [`DateTimeWith::microsecond`] or [`DateTimeWith::nanosecond`] are set.
4380 ///
4381 /// # Example
4382 ///
4383 /// This shows the relationship between constructing a `DateTime` value
4384 /// with subsecond nanoseconds and its individual subsecond fields:
4385 ///
4386 /// ```
4387 /// use jiff::civil::time;
4388 ///
4389 /// let dt1 = time(15, 21, 35, 0).on(2010, 6, 1);
4390 /// let dt2 = dt1.with().subsec_nanosecond(123_456_789).build()?;
4391 /// assert_eq!(dt2.millisecond(), 123);
4392 /// assert_eq!(dt2.microsecond(), 456);
4393 /// assert_eq!(dt2.nanosecond(), 789);
4394 ///
4395 /// # Ok::<(), Box<dyn std::error::Error>>(())
4396 /// ```
4397 #[inline]
4398 pub fn subsec_nanosecond(self, subsec_nanosecond: i32) -> DateTimeWith {
4399 DateTimeWith {
4400 time_with: self.time_with.subsec_nanosecond(subsec_nanosecond),
4401 ..self
4402 }
4403 }
4404}
4405
4406#[cfg(test)]
4407mod tests {
4408 use std::io::Cursor;
4409
4410 use crate::{
4411 RoundMode, ToSpan, Unit,
4412 civil::{date, time},
4413 span::span_eq,
4414 };
4415
4416 use super::*;
4417
4418 #[test]
4419 fn from_temporal_docs() {
4420 let dt = DateTime::from_parts(
4421 date(1995, 12, 7),
4422 time(3, 24, 30, 000_003_500),
4423 );
4424
4425 let got = dt.round(Unit::Hour).unwrap();
4426 let expected =
4427 DateTime::from_parts(date(1995, 12, 7), time(3, 0, 0, 0));
4428 assert_eq!(got, expected);
4429
4430 let got = dt.round((Unit::Minute, 30)).unwrap();
4431 let expected =
4432 DateTime::from_parts(date(1995, 12, 7), time(3, 30, 0, 0));
4433 assert_eq!(got, expected);
4434
4435 let got = dt
4436 .round(
4437 DateTimeRound::new()
4438 .smallest(Unit::Minute)
4439 .increment(30)
4440 .mode(RoundMode::Floor),
4441 )
4442 .unwrap();
4443 let expected =
4444 DateTime::from_parts(date(1995, 12, 7), time(3, 0, 0, 0));
4445 assert_eq!(got, expected);
4446 }
4447
4448 #[test]
4449 fn since() {
4450 let later = date(2024, 5, 9).at(2, 0, 0, 0);
4451 let earlier = date(2024, 5, 8).at(3, 0, 0, 0);
4452 span_eq!(later.since(earlier).unwrap(), 23.hours());
4453
4454 let later = date(2024, 5, 9).at(3, 0, 0, 0);
4455 let earlier = date(2024, 5, 8).at(2, 0, 0, 0);
4456 span_eq!(later.since(earlier).unwrap(), 1.days().hours(1));
4457
4458 let later = date(2024, 5, 9).at(2, 0, 0, 0);
4459 let earlier = date(2024, 5, 10).at(3, 0, 0, 0);
4460 span_eq!(later.since(earlier).unwrap(), -1.days().hours(1));
4461
4462 let later = date(2024, 5, 9).at(3, 0, 0, 0);
4463 let earlier = date(2024, 5, 10).at(2, 0, 0, 0);
4464 span_eq!(later.since(earlier).unwrap(), -23.hours());
4465 }
4466
4467 #[test]
4468 fn until() {
4469 let a = date(9999, 12, 30).at(3, 0, 0, 0);
4470 let b = date(9999, 12, 31).at(2, 0, 0, 0);
4471 span_eq!(a.until(b).unwrap(), 23.hours());
4472
4473 let a = date(-9999, 1, 2).at(2, 0, 0, 0);
4474 let b = date(-9999, 1, 1).at(3, 0, 0, 0);
4475 span_eq!(a.until(b).unwrap(), -23.hours());
4476
4477 let a = date(1995, 12, 7).at(3, 24, 30, 3500);
4478 let b = date(2019, 1, 31).at(15, 30, 0, 0);
4479 span_eq!(
4480 a.until(b).unwrap(),
4481 8456.days()
4482 .hours(12)
4483 .minutes(5)
4484 .seconds(29)
4485 .milliseconds(999)
4486 .microseconds(996)
4487 .nanoseconds(500)
4488 );
4489 span_eq!(
4490 a.until((Unit::Year, b)).unwrap(),
4491 23.years()
4492 .months(1)
4493 .days(24)
4494 .hours(12)
4495 .minutes(5)
4496 .seconds(29)
4497 .milliseconds(999)
4498 .microseconds(996)
4499 .nanoseconds(500)
4500 );
4501 span_eq!(
4502 b.until((Unit::Year, a)).unwrap(),
4503 -23.years()
4504 .months(1)
4505 .days(24)
4506 .hours(12)
4507 .minutes(5)
4508 .seconds(29)
4509 .milliseconds(999)
4510 .microseconds(996)
4511 .nanoseconds(500)
4512 );
4513 span_eq!(
4514 a.until((Unit::Nanosecond, b)).unwrap(),
4515 730641929999996500i64.nanoseconds(),
4516 );
4517
4518 let a = date(-9999, 1, 1).at(0, 0, 0, 0);
4519 let b = date(9999, 12, 31).at(23, 59, 59, 999_999_999);
4520 assert!(a.until((Unit::Nanosecond, b)).is_err());
4521 span_eq!(
4522 a.until((Unit::Microsecond, b)).unwrap(),
4523 Span::new()
4524 .microseconds(631_107_417_600_000_000i64 - 1)
4525 .nanoseconds(999),
4526 );
4527 }
4528
4529 #[test]
4530 fn until_month_lengths() {
4531 let jan1 = date(2020, 1, 1).at(0, 0, 0, 0);
4532 let feb1 = date(2020, 2, 1).at(0, 0, 0, 0);
4533 let mar1 = date(2020, 3, 1).at(0, 0, 0, 0);
4534
4535 span_eq!(jan1.until(feb1).unwrap(), 31.days());
4536 span_eq!(jan1.until((Unit::Month, feb1)).unwrap(), 1.month());
4537 span_eq!(feb1.until(mar1).unwrap(), 29.days());
4538 span_eq!(feb1.until((Unit::Month, mar1)).unwrap(), 1.month());
4539 span_eq!(jan1.until(mar1).unwrap(), 60.days());
4540 span_eq!(jan1.until((Unit::Month, mar1)).unwrap(), 2.months());
4541 }
4542
4543 #[test]
4544 fn datetime_size() {
4545 #[cfg(debug_assertions)]
4546 {
4547 assert_eq!(12, core::mem::size_of::<DateTime>());
4548 }
4549 #[cfg(not(debug_assertions))]
4550 {
4551 assert_eq!(12, core::mem::size_of::<DateTime>());
4552 }
4553 }
4554
4555 /// # `serde` deserializer compatibility test
4556 ///
4557 /// Serde YAML used to be unable to deserialize `jiff` types,
4558 /// as deserializing from bytes is not supported by the deserializer.
4559 ///
4560 /// - <https://github.com/BurntSushi/jiff/issues/138>
4561 /// - <https://github.com/BurntSushi/jiff/discussions/148>
4562 #[test]
4563 fn civil_datetime_deserialize_yaml() {
4564 let expected = datetime(2024, 10, 31, 16, 33, 53, 123456789);
4565
4566 let deserialized: DateTime =
4567 serde_yaml::from_str("2024-10-31 16:33:53.123456789").unwrap();
4568
4569 assert_eq!(deserialized, expected);
4570
4571 let deserialized: DateTime =
4572 serde_yaml::from_slice("2024-10-31 16:33:53.123456789".as_bytes())
4573 .unwrap();
4574
4575 assert_eq!(deserialized, expected);
4576
4577 let cursor = Cursor::new(b"2024-10-31 16:33:53.123456789");
4578 let deserialized: DateTime = serde_yaml::from_reader(cursor).unwrap();
4579
4580 assert_eq!(deserialized, expected);
4581 }
4582}