1#![forbid(unsafe_code)]
21
22pub mod format;
23mod parse;
24
25use std::fmt;
26use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
27use std::str::FromStr;
28
29pub use jiff;
30use jiff::civil;
31use jiff::tz::TimeZone;
32use jiff::{SignedDuration, Timestamp};
33
34pub use parse::ParseError;
35
36pub use jiff::civil::Date;
38pub use jiff::civil::DateTime as CivilDateTime;
40pub use jiff::civil::Time;
42
43pub fn parse_date(s: &str, fmt: &str) -> Result<Date, ParseError> {
49 if s.starts_with(['+', '-']) {
50 return Err(ParseError::invalid());
51 }
52 Date::strptime(fmt, s).map_err(|_| ParseError::invalid())
53}
54
55pub fn parse_civil_datetime(s: &str, fmt: &str) -> Result<CivilDateTime, ParseError> {
58 if s.starts_with(['+', '-']) {
59 return Err(ParseError::invalid());
60 }
61 CivilDateTime::strptime(fmt, s).map_err(|_| ParseError::invalid())
62}
63
64#[must_use]
66pub fn utc_from_civil(dt: CivilDateTime) -> Option<UtcDateTime> {
67 dt.to_zoned(TimeZone::UTC)
68 .ok()
69 .map(|z| UtcDateTime(z.timestamp()))
70}
71
72#[must_use]
76pub fn utc_from_local_civil(dt: CivilDateTime) -> Option<UtcDateTime> {
77 use jiff::tz::AmbiguousOffset;
78 let offset = match TimeZone::system().to_ambiguous_timestamp(dt).offset() {
79 AmbiguousOffset::Unambiguous { offset } | AmbiguousOffset::Fold { before: offset, .. } => {
80 offset
81 }
82 AmbiguousOffset::Gap { .. } => return utc_from_civil(dt),
83 };
84 offset.to_timestamp(dt).ok().map(UtcDateTime)
85}
86
87#[must_use]
90pub fn days_between(earlier: Date, later: Date) -> i64 {
91 i64::from((later - earlier).get_days())
92}
93
94macro_rules! civil_ops {
97 ($t:ty) => {
98 impl Add<Duration> for $t {
99 type Output = $t;
100 fn add(self, d: Duration) -> $t {
101 self.checked_add(d.0).expect(concat!(
102 "`",
103 stringify!($t),
104 " + Duration` overflowed"
105 ))
106 }
107 }
108 impl Sub<Duration> for $t {
109 type Output = $t;
110 fn sub(self, d: Duration) -> $t {
111 self.checked_sub(d.0).expect(concat!(
112 "`",
113 stringify!($t),
114 " - Duration` overflowed"
115 ))
116 }
117 }
118 };
119}
120civil_ops!(Date);
121civil_ops!(CivilDateTime);
122
123const NANOS_PER_SEC: i128 = 1_000_000_000;
124
125#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
127pub enum SecondsFormat {
128 Secs,
130 Millis,
132 Micros,
134 Nanos,
136 AutoSi,
138}
139
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub struct OutOfRangeError;
143
144impl fmt::Display for OutOfRangeError {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 f.write_str("out of range")
147 }
148}
149
150impl std::error::Error for OutOfRangeError {}
151
152#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
158pub struct UtcDateTime(Timestamp);
159
160impl Default for UtcDateTime {
161 fn default() -> Self {
163 Self::UNIX_EPOCH
164 }
165}
166
167impl UtcDateTime {
168 pub const UNIX_EPOCH: Self = Self(Timestamp::UNIX_EPOCH);
170
171 #[must_use]
173 pub fn now() -> Self {
174 Self(Timestamp::now())
175 }
176
177 #[must_use]
179 pub fn with_ymd_and_hms(
180 year: i32,
181 month: u32,
182 day: u32,
183 hour: u32,
184 minute: u32,
185 second: u32,
186 ) -> Option<Self> {
187 let date = civil::Date::new(
188 i16::try_from(year).ok()?,
189 i8::try_from(month).ok()?,
190 i8::try_from(day).ok()?,
191 )
192 .ok()?;
193 let time = civil::Time::new(
194 i8::try_from(hour).ok()?,
195 i8::try_from(minute).ok()?,
196 i8::try_from(second).ok()?,
197 0,
198 )
199 .ok()?;
200 date.to_datetime(time)
201 .to_zoned(TimeZone::UTC)
202 .ok()
203 .map(|z| Self(z.timestamp()))
204 }
205
206 #[must_use]
208 pub const fn from_jiff(ts: Timestamp) -> Self {
209 Self(ts)
210 }
211
212 #[must_use]
214 pub const fn as_jiff(self) -> Timestamp {
215 self.0
216 }
217
218 #[must_use]
221 pub fn from_timestamp(secs: i64, nanos: u32) -> Option<Self> {
222 if nanos >= 1_000_000_000 {
223 return None;
224 }
225 Self::from_nanos_i128(i128::from(secs) * NANOS_PER_SEC + i128::from(nanos))
226 }
227
228 #[must_use]
230 pub fn from_timestamp_millis(millis: i64) -> Option<Self> {
231 Self::from_nanos_i128(i128::from(millis) * 1_000_000)
232 }
233
234 #[must_use]
236 pub fn from_timestamp_micros(micros: i64) -> Option<Self> {
237 Self::from_nanos_i128(i128::from(micros) * 1_000)
238 }
239
240 #[must_use]
242 pub fn from_timestamp_nanos(nanos: i64) -> Self {
243 Self::from_nanos_i128(i128::from(nanos)).expect("every i64 nanosecond count is in range")
244 }
245
246 fn from_nanos_i128(nanos: i128) -> Option<Self> {
247 Timestamp::from_nanosecond(nanos).ok().map(Self)
248 }
249
250 fn nanos_i128(self) -> i128 {
251 self.0.as_nanosecond()
252 }
253
254 #[must_use]
256 pub fn timestamp(self) -> i64 {
257 to_i64(self.nanos_i128().div_euclid(NANOS_PER_SEC))
258 }
259
260 #[must_use]
262 pub fn timestamp_millis(self) -> i64 {
263 to_i64(self.nanos_i128().div_euclid(1_000_000))
264 }
265
266 #[must_use]
268 pub fn timestamp_micros(self) -> i64 {
269 to_i64(self.nanos_i128().div_euclid(1_000))
270 }
271
272 #[must_use]
274 pub fn timestamp_nanos_opt(self) -> Option<i64> {
275 i64::try_from(self.nanos_i128()).ok()
276 }
277
278 #[must_use]
280 pub fn timestamp_subsec_nanos(self) -> u32 {
281 u32::try_from(self.nanos_i128().rem_euclid(NANOS_PER_SEC)).expect("below one second")
282 }
283
284 #[must_use]
286 pub fn timestamp_subsec_millis(self) -> u32 {
287 self.timestamp_subsec_nanos() / 1_000_000
288 }
289
290 #[must_use]
292 pub fn timestamp_subsec_micros(self) -> u32 {
293 self.timestamp_subsec_nanos() / 1_000
294 }
295
296 pub fn parse_from_rfc3339(s: &str) -> Result<Self, ParseError> {
300 parse::rfc3339(s, parse::Mode::Strict).map(|p| p.utc)
301 }
302
303 pub fn parse_from_str(s: &str, fmt: &str) -> Result<Self, ParseError> {
306 Timestamp::strptime(fmt, s)
307 .map(Self)
308 .map_err(|_| ParseError::invalid())
309 }
310
311 #[must_use]
313 pub fn to_rfc3339(self) -> String {
314 self.to_rfc3339_opts(SecondsFormat::AutoSi, false)
315 }
316
317 #[must_use]
320 pub fn to_rfc3339_opts(self, secform: SecondsFormat, use_z: bool) -> String {
321 let mut out = String::with_capacity(32);
322 let parts = format::Parts::utc(self);
323 format::write_rfc3339(
324 &mut out,
325 &parts,
326 secform,
327 if use_z { "Z" } else { "+00:00" },
328 );
329 out
330 }
331
332 #[must_use]
334 pub fn format(self, fmt: &str) -> format::Formatted<'_> {
335 format::Formatted::new(format::Parts::utc(self), fmt)
336 }
337
338 #[must_use]
340 pub fn date_naive(self) -> civil::Date {
341 self.civil().date()
342 }
343
344 #[must_use]
346 pub fn naive_utc(self) -> civil::DateTime {
347 self.civil()
348 }
349
350 fn civil(self) -> civil::DateTime {
351 TimeZone::UTC.to_datetime(self.0)
352 }
353
354 #[must_use]
356 pub fn year(self) -> i32 {
357 i32::from(self.civil().year())
358 }
359
360 #[must_use]
362 pub fn month(self) -> u32 {
363 u32::try_from(self.civil().month()).expect("month is positive")
364 }
365
366 #[must_use]
368 pub fn day(self) -> u32 {
369 u32::try_from(self.civil().day()).expect("day is positive")
370 }
371
372 #[must_use]
374 pub fn hour(self) -> u32 {
375 u32::try_from(self.civil().hour()).expect("hour is not negative")
376 }
377
378 #[must_use]
380 pub fn minute(self) -> u32 {
381 u32::try_from(self.civil().minute()).expect("minute is not negative")
382 }
383
384 #[must_use]
386 pub fn second(self) -> u32 {
387 u32::try_from(self.civil().second()).expect("second is not negative")
388 }
389
390 #[must_use]
392 pub fn ordinal(self) -> u32 {
393 u32::try_from(self.civil().day_of_year()).expect("day of year is positive")
394 }
395
396 #[must_use]
398 pub fn weekday_from_monday(self) -> u32 {
399 u32::try_from(self.civil().weekday().to_monday_zero_offset()).expect("0..=6")
400 }
401
402 #[must_use]
404 pub fn to_local(self) -> LocalDateTime {
405 LocalDateTime(self.0.to_zoned(TimeZone::system()))
406 }
407
408 #[must_use]
410 pub const fn fixed_offset(self) -> OffsetDateTime {
411 OffsetDateTime {
412 utc: self,
413 offset_secs: 0,
414 }
415 }
416
417 #[must_use]
420 pub fn with_offset_seconds(self, secs: i32) -> Option<OffsetDateTime> {
421 (-86_399..=86_399)
422 .contains(&secs)
423 .then_some(OffsetDateTime {
424 utc: self,
425 offset_secs: secs,
426 })
427 }
428
429 pub fn duration_trunc(self, span: Duration) -> Result<Self, OutOfRangeError> {
433 let span = span.0.as_nanos();
434 let stamp = self.nanos_i128();
435 if span <= 0 || span > stamp.abs() {
436 return Err(OutOfRangeError);
437 }
438 Self::from_nanos_i128(stamp - stamp.rem_euclid(span)).ok_or(OutOfRangeError)
439 }
440
441 #[must_use]
444 pub fn with_nanosecond(self, nano: u32) -> Option<Self> {
445 if i128::from(nano) >= NANOS_PER_SEC {
446 return None;
447 }
448 let secs = i128::from(self.timestamp());
449 Self::from_nanos_i128(secs * NANOS_PER_SEC + i128::from(nano))
450 }
451
452 #[must_use]
455 pub const fn to_utc(self) -> Self {
456 self
457 }
458
459 #[must_use]
461 pub fn signed_duration_since(self, other: impl Into<UtcDateTime>) -> Duration {
462 Duration::from_nanos_i128(self.nanos_i128() - other.into().nanos_i128())
463 .expect("the difference of two instants fits a duration")
464 }
465
466 #[must_use]
468 pub fn checked_add_signed(self, d: Duration) -> Option<Self> {
469 self.0.checked_add(d.0).ok().map(Self)
470 }
471
472 #[must_use]
474 pub fn checked_sub_signed(self, d: Duration) -> Option<Self> {
475 self.0.checked_sub(d.0).ok().map(Self)
476 }
477
478 #[must_use]
480 pub fn trunc_subsecs_to_secs(self) -> Self {
481 Self::from_nanos_i128(self.nanos_i128() - self.nanos_i128().rem_euclid(NANOS_PER_SEC))
482 .expect("truncation stays in range")
483 }
484
485 #[must_use]
487 pub fn to_system_time(self) -> std::time::SystemTime {
488 std::time::SystemTime::from(self.0)
489 }
490}
491
492fn to_i64(v: i128) -> i64 {
493 i64::try_from(v).expect("jiff's range fits i64 at this resolution")
494}
495
496impl From<std::time::SystemTime> for UtcDateTime {
497 fn from(t: std::time::SystemTime) -> Self {
500 Self(Timestamp::try_from(t).expect("system time within years -9999..=9999"))
501 }
502}
503
504impl From<UtcDateTime> for std::time::SystemTime {
505 fn from(t: UtcDateTime) -> Self {
506 t.to_system_time()
507 }
508}
509
510impl From<Timestamp> for UtcDateTime {
511 fn from(ts: Timestamp) -> Self {
512 Self(ts)
513 }
514}
515
516impl From<UtcDateTime> for Timestamp {
517 fn from(t: UtcDateTime) -> Self {
518 t.0
519 }
520}
521
522impl fmt::Debug for UtcDateTime {
523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524 f.write_str(&self.to_rfc3339_opts(SecondsFormat::AutoSi, true))
525 }
526}
527
528impl fmt::Display for UtcDateTime {
529 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532 let mut out = String::with_capacity(32);
533 format::write_display(&mut out, &format::Parts::utc(*self));
534 f.pad(&out)
535 }
536}
537
538impl FromStr for UtcDateTime {
539 type Err = ParseError;
540
541 fn from_str(s: &str) -> Result<Self, ParseError> {
543 parse::rfc3339(s, parse::Mode::Relaxed).map(|p| p.utc)
544 }
545}
546
547impl serde::Serialize for UtcDateTime {
548 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
549 serializer.collect_str(&format_args!("{self:?}"))
550 }
551}
552
553impl<'de> serde::Deserialize<'de> for UtcDateTime {
554 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
555 struct Visitor;
556 impl serde::de::Visitor<'_> for Visitor {
557 type Value = UtcDateTime;
558 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559 f.write_str("an RFC 3339 date and time string")
560 }
561 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<UtcDateTime, E> {
562 v.parse().map_err(E::custom)
563 }
564 }
565 deserializer.deserialize_str(Visitor)
566 }
567}
568
569#[cfg(feature = "schemars")]
572impl schemars::JsonSchema for UtcDateTime {
573 fn inline_schema() -> bool {
574 true
575 }
576
577 fn schema_name() -> std::borrow::Cow<'static, str> {
578 "DateTime".into()
579 }
580
581 fn schema_id() -> std::borrow::Cow<'static, str> {
582 "chrono::DateTime".into()
583 }
584
585 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
586 schemars::json_schema!({
587 "type": "string",
588 "format": "date-time"
589 })
590 }
591}
592
593impl Add<Duration> for UtcDateTime {
594 type Output = Self;
595 fn add(self, d: Duration) -> Self {
596 self.checked_add_signed(d)
597 .expect("`UtcDateTime + Duration` overflowed")
598 }
599}
600
601impl Sub<Duration> for UtcDateTime {
602 type Output = Self;
603 fn sub(self, d: Duration) -> Self {
604 self.checked_sub_signed(d)
605 .expect("`UtcDateTime - Duration` overflowed")
606 }
607}
608
609impl AddAssign<Duration> for UtcDateTime {
610 fn add_assign(&mut self, d: Duration) {
611 *self = *self + d;
612 }
613}
614
615impl SubAssign<Duration> for UtcDateTime {
616 fn sub_assign(&mut self, d: Duration) {
617 *self = *self - d;
618 }
619}
620
621impl Add<std::time::Duration> for UtcDateTime {
622 type Output = Self;
623 fn add(self, d: std::time::Duration) -> Self {
624 self + Duration::from_std(d).expect("std duration within range")
625 }
626}
627
628impl Sub<std::time::Duration> for UtcDateTime {
629 type Output = Self;
630 fn sub(self, d: std::time::Duration) -> Self {
631 self - Duration::from_std(d).expect("std duration within range")
632 }
633}
634
635impl Sub for UtcDateTime {
636 type Output = Duration;
637 fn sub(self, other: Self) -> Duration {
638 self.signed_duration_since(other)
639 }
640}
641
642#[derive(Clone, Copy)]
651pub struct OffsetDateTime {
652 utc: UtcDateTime,
653 offset_secs: i32,
654}
655
656impl OffsetDateTime {
657 pub fn parse_from_rfc3339(s: &str) -> Result<Self, ParseError> {
659 parse::rfc3339(s, parse::Mode::Strict).map(|p| Self {
660 utc: p.utc,
661 offset_secs: p.offset_secs,
662 })
663 }
664
665 #[must_use]
667 pub const fn to_utc(self) -> UtcDateTime {
668 self.utc
669 }
670
671 #[must_use]
673 pub const fn offset_seconds(self) -> i32 {
674 self.offset_secs
675 }
676
677 #[must_use]
679 pub fn timestamp(self) -> i64 {
680 self.utc.timestamp()
681 }
682
683 #[must_use]
685 pub fn timestamp_millis(self) -> i64 {
686 self.utc.timestamp_millis()
687 }
688
689 #[must_use]
691 pub fn signed_duration_since(self, other: impl Into<UtcDateTime>) -> Duration {
692 self.utc.signed_duration_since(other)
693 }
694
695 #[must_use]
697 pub fn checked_add_signed(self, d: Duration) -> Option<Self> {
698 self.utc
699 .checked_add_signed(d)
700 .map(|utc| Self { utc, ..self })
701 }
702
703 #[must_use]
705 pub fn checked_sub_signed(self, d: Duration) -> Option<Self> {
706 self.utc
707 .checked_sub_signed(d)
708 .map(|utc| Self { utc, ..self })
709 }
710
711 #[must_use]
713 pub fn to_rfc3339(self) -> String {
714 self.to_rfc3339_opts(SecondsFormat::AutoSi, false)
715 }
716
717 #[must_use]
720 pub fn to_rfc3339_opts(self, secform: SecondsFormat, use_z: bool) -> String {
721 let mut out = String::with_capacity(32);
722 let parts = format::Parts::with_offset(self.utc, self.offset_secs, None);
723 let offset = if use_z && self.offset_secs == 0 {
724 "Z".to_owned()
725 } else {
726 format::offset_colon(self.offset_secs)
727 };
728 format::write_rfc3339(&mut out, &parts, secform, &offset);
729 out
730 }
731
732 #[must_use]
734 pub fn timestamp_subsec_nanos(self) -> u32 {
735 self.utc.timestamp_subsec_nanos()
736 }
737
738 #[must_use]
740 pub fn to_local(self) -> LocalDateTime {
741 self.utc.to_local()
742 }
743
744 #[must_use]
746 pub fn format(self, fmt: &str) -> format::Formatted<'_> {
747 format::Formatted::new(
748 format::Parts::with_offset(self.utc, self.offset_secs, None),
749 fmt,
750 )
751 }
752}
753
754impl From<OffsetDateTime> for UtcDateTime {
755 fn from(t: OffsetDateTime) -> Self {
756 t.utc
757 }
758}
759
760impl PartialEq for OffsetDateTime {
761 fn eq(&self, other: &Self) -> bool {
762 self.utc == other.utc
763 }
764}
765
766impl Eq for OffsetDateTime {}
767
768impl std::hash::Hash for OffsetDateTime {
769 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
770 self.utc.hash(state);
771 }
772}
773
774impl PartialEq<UtcDateTime> for OffsetDateTime {
775 fn eq(&self, other: &UtcDateTime) -> bool {
776 self.utc == *other
777 }
778}
779
780impl PartialEq<OffsetDateTime> for UtcDateTime {
781 fn eq(&self, other: &OffsetDateTime) -> bool {
782 *self == other.utc
783 }
784}
785
786impl PartialOrd<UtcDateTime> for OffsetDateTime {
787 fn partial_cmp(&self, other: &UtcDateTime) -> Option<std::cmp::Ordering> {
788 Some(self.utc.cmp(other))
789 }
790}
791
792impl PartialOrd<OffsetDateTime> for UtcDateTime {
793 fn partial_cmp(&self, other: &OffsetDateTime) -> Option<std::cmp::Ordering> {
794 Some(self.cmp(&other.utc))
795 }
796}
797
798impl Sub for OffsetDateTime {
799 type Output = Duration;
800 fn sub(self, other: Self) -> Duration {
801 self.utc.signed_duration_since(other)
802 }
803}
804
805impl Sub<UtcDateTime> for OffsetDateTime {
806 type Output = Duration;
807 fn sub(self, other: UtcDateTime) -> Duration {
808 self.utc.signed_duration_since(other)
809 }
810}
811
812impl Sub<OffsetDateTime> for UtcDateTime {
813 type Output = Duration;
814 fn sub(self, other: OffsetDateTime) -> Duration {
815 self.signed_duration_since(other)
816 }
817}
818
819impl Add<Duration> for OffsetDateTime {
820 type Output = Self;
821 fn add(self, d: Duration) -> Self {
822 self.checked_add_signed(d)
823 .expect("`OffsetDateTime + Duration` overflowed")
824 }
825}
826
827impl Sub<Duration> for OffsetDateTime {
828 type Output = Self;
829 fn sub(self, d: Duration) -> Self {
830 self.checked_sub_signed(d)
831 .expect("`OffsetDateTime - Duration` overflowed")
832 }
833}
834
835impl Ord for OffsetDateTime {
836 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
837 self.utc.cmp(&other.utc)
838 }
839}
840
841impl PartialOrd for OffsetDateTime {
842 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
843 Some(self.cmp(other))
844 }
845}
846
847impl fmt::Debug for OffsetDateTime {
848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 f.write_str(&self.to_rfc3339())
850 }
851}
852
853impl fmt::Display for OffsetDateTime {
854 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856 let s = self.format("%Y-%m-%d %H:%M:%S%.f %:z").to_string();
857 f.pad(&s)
858 }
859}
860
861#[derive(Clone, PartialEq, Eq)]
867pub struct LocalDateTime(jiff::Zoned);
868
869impl LocalDateTime {
870 #[must_use]
872 pub fn now() -> Self {
873 Self(jiff::Zoned::now())
874 }
875
876 #[must_use]
878 pub fn to_utc(&self) -> UtcDateTime {
879 UtcDateTime(self.0.timestamp())
880 }
881
882 #[must_use]
884 pub fn offset_seconds(&self) -> i32 {
885 self.0.offset().seconds()
886 }
887
888 #[must_use]
890 pub fn date_naive(&self) -> civil::Date {
891 self.0.date()
892 }
893
894 #[must_use]
896 pub fn naive_local(&self) -> civil::DateTime {
897 self.0.datetime()
898 }
899
900 #[must_use]
902 pub fn hour(&self) -> u32 {
903 u32::try_from(self.0.hour()).expect("hour is not negative")
904 }
905
906 #[must_use]
908 pub fn to_rfc3339(&self) -> String {
909 let mut out = String::with_capacity(32);
910 let parts = self.parts();
911 let offset = format::offset_colon(self.offset_seconds());
912 format::write_rfc3339(&mut out, &parts, SecondsFormat::AutoSi, &offset);
913 out
914 }
915
916 #[must_use]
918 pub fn format<'a>(&self, fmt: &'a str) -> format::Formatted<'a> {
919 format::Formatted::new(self.parts(), fmt)
920 }
921
922 fn parts(&self) -> format::Parts {
923 format::Parts::with_offset(self.to_utc(), self.offset_seconds(), None)
924 }
925
926 #[must_use]
928 pub fn as_jiff(&self) -> &jiff::Zoned {
929 &self.0
930 }
931}
932
933impl fmt::Debug for LocalDateTime {
934 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
935 f.write_str(&self.to_rfc3339())
936 }
937}
938
939impl fmt::Display for LocalDateTime {
940 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942 let s = self.format("%Y-%m-%d %H:%M:%S%.f %:z").to_string();
943 f.pad(&s)
944 }
945}
946
947#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
953pub struct Duration(SignedDuration);
954
955macro_rules! ctor {
956 ($(#[$doc:meta])* $name:ident, $try_name:ident, $nanos:expr) => {
957 $(#[$doc])*
958 #[must_use]
960 pub const fn $name(n: i64) -> Self {
961 match Self::$try_name(n) {
962 Some(d) => d,
963 None => panic!(concat!("Duration::", stringify!($name), " out of bounds")),
964 }
965 }
966
967 $(#[$doc])*
968 #[must_use]
970 #[allow(clippy::cast_lossless)] pub const fn $try_name(n: i64) -> Option<Self> {
972 Self::from_nanos_i128(n as i128 * $nanos)
973 }
974 };
975}
976
977impl Duration {
978 pub const ZERO: Self = Self(SignedDuration::ZERO);
980
981 #[must_use]
983 pub const fn zero() -> Self {
984 Self::ZERO
985 }
986
987 ctor!(
988 weeks,
990 try_weeks,
991 7 * 86_400 * NANOS_PER_SEC
992 );
993 ctor!(
994 days,
996 try_days,
997 86_400 * NANOS_PER_SEC
998 );
999 ctor!(
1000 hours,
1002 try_hours,
1003 3_600 * NANOS_PER_SEC
1004 );
1005 ctor!(
1006 minutes,
1008 try_minutes,
1009 60 * NANOS_PER_SEC
1010 );
1011 ctor!(
1012 seconds,
1014 try_seconds,
1015 NANOS_PER_SEC
1016 );
1017 ctor!(
1018 milliseconds,
1020 try_milliseconds,
1021 1_000_000
1022 );
1023 ctor!(
1024 microseconds,
1026 try_microseconds,
1027 1_000
1028 );
1029
1030 #[must_use]
1032 pub fn nanoseconds(n: i64) -> Self {
1033 Self(SignedDuration::from_nanos(n))
1034 }
1035
1036 pub const MAX: Self = Self(SignedDuration::new(
1039 i64::MAX / 1_000,
1040 (i64::MAX % 1_000) as i32 * 1_000_000,
1041 ));
1042 pub const MIN: Self = Self(SignedDuration::new(
1044 -(i64::MAX / 1_000),
1045 -((i64::MAX % 1_000) as i32 * 1_000_000),
1046 ));
1047
1048 #[allow(clippy::cast_possible_truncation)]
1050 const fn from_nanos_i128(nanos: i128) -> Option<Self> {
1051 const LIMIT: i128 = i64::MAX as i128 * 1_000_000;
1052 if nanos < -LIMIT || nanos > LIMIT {
1053 return None;
1054 }
1055 let secs = (nanos / NANOS_PER_SEC) as i64;
1057 let sub = (nanos % NANOS_PER_SEC) as i32;
1058 Some(Self(SignedDuration::new(secs, sub)))
1059 }
1060
1061 fn nanos_i128(self) -> i128 {
1062 self.0.as_nanos()
1063 }
1064
1065 #[must_use]
1067 pub fn num_weeks(self) -> i64 {
1068 self.num_days() / 7
1069 }
1070
1071 #[must_use]
1073 pub fn num_days(self) -> i64 {
1074 self.num_seconds() / 86_400
1075 }
1076
1077 #[must_use]
1079 pub fn num_hours(self) -> i64 {
1080 self.num_seconds() / 3_600
1081 }
1082
1083 #[must_use]
1085 pub fn num_minutes(self) -> i64 {
1086 self.num_seconds() / 60
1087 }
1088
1089 #[must_use]
1091 pub fn num_seconds(self) -> i64 {
1092 self.0.as_secs()
1093 }
1094
1095 #[must_use]
1097 pub fn num_milliseconds(self) -> i64 {
1098 i64::try_from(self.nanos_i128() / 1_000_000)
1099 .expect("milliseconds of an i64-second span fit i64")
1100 }
1101
1102 #[must_use]
1104 pub fn num_microseconds(self) -> Option<i64> {
1105 i64::try_from(self.nanos_i128() / 1_000).ok()
1106 }
1107
1108 #[must_use]
1110 pub fn num_nanoseconds(self) -> Option<i64> {
1111 i64::try_from(self.nanos_i128()).ok()
1112 }
1113
1114 #[must_use]
1116 pub fn subsec_nanos(self) -> i32 {
1117 self.0.subsec_nanos()
1118 }
1119
1120 #[must_use]
1122 pub fn as_seconds_f64(self) -> f64 {
1123 self.0.as_secs_f64()
1124 }
1125
1126 #[must_use]
1128 pub fn is_zero(self) -> bool {
1129 self.0.is_zero()
1130 }
1131
1132 #[must_use]
1134 pub fn is_negative(self) -> bool {
1135 self.0.is_negative()
1136 }
1137
1138 #[must_use]
1140 pub fn abs(self) -> Self {
1141 Self(self.0.abs())
1142 }
1143
1144 #[must_use]
1146 pub fn checked_add(&self, rhs: &Self) -> Option<Self> {
1147 Self::from_nanos_i128(self.nanos_i128() + rhs.nanos_i128())
1148 }
1149
1150 #[must_use]
1152 pub fn checked_sub(&self, rhs: &Self) -> Option<Self> {
1153 Self::from_nanos_i128(self.nanos_i128() - rhs.nanos_i128())
1154 }
1155
1156 pub fn from_std(d: std::time::Duration) -> Result<Self, OutOfRangeError> {
1158 Self::from_nanos_i128(i128::try_from(d.as_nanos()).map_err(|_| OutOfRangeError)?)
1159 .ok_or(OutOfRangeError)
1160 }
1161
1162 pub fn to_std(self) -> Result<std::time::Duration, OutOfRangeError> {
1164 std::time::Duration::try_from(self.0).map_err(|_| OutOfRangeError)
1165 }
1166
1167 #[must_use]
1169 pub const fn from_jiff(d: SignedDuration) -> Self {
1170 Self(d)
1171 }
1172
1173 #[must_use]
1175 pub const fn as_jiff(self) -> SignedDuration {
1176 self.0
1177 }
1178}
1179
1180impl Add for Duration {
1181 type Output = Self;
1182 fn add(self, rhs: Self) -> Self {
1183 self.checked_add(&rhs)
1184 .expect("`Duration + Duration` overflowed")
1185 }
1186}
1187
1188impl Sub for Duration {
1189 type Output = Self;
1190 fn sub(self, rhs: Self) -> Self {
1191 self.checked_sub(&rhs)
1192 .expect("`Duration - Duration` overflowed")
1193 }
1194}
1195
1196impl AddAssign for Duration {
1197 fn add_assign(&mut self, rhs: Self) {
1198 *self = *self + rhs;
1199 }
1200}
1201
1202impl SubAssign for Duration {
1203 fn sub_assign(&mut self, rhs: Self) {
1204 *self = *self - rhs;
1205 }
1206}
1207
1208impl Neg for Duration {
1209 type Output = Self;
1210 fn neg(self) -> Self {
1211 Self(-self.0)
1212 }
1213}
1214
1215impl Mul<i32> for Duration {
1216 type Output = Self;
1217 fn mul(self, rhs: i32) -> Self {
1218 Self::from_nanos_i128(self.nanos_i128() * i128::from(rhs))
1219 .expect("`Duration * i32` overflowed")
1220 }
1221}
1222
1223impl Div<i32> for Duration {
1224 type Output = Self;
1225 fn div(self, rhs: i32) -> Self {
1226 assert!(rhs != 0, "`Duration / i32` divided by zero");
1227 let total = self.nanos_i128();
1231 let (secs, nanos) = (
1232 total.div_euclid(NANOS_PER_SEC),
1233 total.rem_euclid(NANOS_PER_SEC),
1234 );
1235 let rhs = i128::from(rhs);
1236 let mut q_secs = secs / rhs;
1237 let carry = secs % rhs;
1238 let mut q_nanos = nanos / rhs + carry * NANOS_PER_SEC / rhs;
1239 if q_nanos < 0 {
1240 q_secs -= 1;
1241 q_nanos += NANOS_PER_SEC;
1242 } else if q_nanos >= NANOS_PER_SEC {
1243 q_secs += 1;
1244 q_nanos -= NANOS_PER_SEC;
1245 }
1246 Self::from_nanos_i128(q_secs * NANOS_PER_SEC + q_nanos).expect("a quotient stays in range")
1247 }
1248}
1249
1250impl std::iter::Sum for Duration {
1251 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1252 iter.fold(Self::ZERO, Add::add)
1253 }
1254}
1255
1256impl<'a> std::iter::Sum<&'a Duration> for Duration {
1257 fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
1258 iter.copied().sum()
1259 }
1260}
1261
1262impl fmt::Debug for Duration {
1263 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1264 fmt::Display::fmt(self, f)
1265 }
1266}
1267
1268impl fmt::Display for Duration {
1269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1271 let nanos = self.nanos_i128();
1272 let sign = if nanos < 0 { "-" } else { "" };
1273 let abs = nanos.unsigned_abs();
1274 if abs == 0 {
1275 return f.write_str("P0D");
1276 }
1277 let secs = abs / 1_000_000_000;
1278 let mut frac = abs % 1_000_000_000;
1279 write!(f, "{sign}PT{secs}")?;
1280 if frac > 0 {
1281 let mut width = 9usize;
1282 while frac.is_multiple_of(10) {
1283 frac /= 10;
1284 width -= 1;
1285 }
1286 write!(f, ".{frac:0width$}")?;
1287 }
1288 f.write_str("S")
1289 }
1290}
1291
1292#[cfg(test)]
1293#[allow(clippy::unwrap_used)]
1294mod tests;