Skip to main content

jiff/civil/
mod.rs

1/*!
2Facilities for dealing with inexact dates and times.
3
4# Overview
5
6The essential types in this module are:
7
8* [`Date`] is a specific day in the proleptic Gregorian calendar.
9* [`Time`] is a specific wall clock time.
10* [`DateTime`] is a combination of a day and a time.
11
12Moreover, the [`date`](date()) and [`time`](time()) free functions can be used
13to conveniently create values of any of three types above:
14
15```
16use jiff::civil::{date, time};
17
18assert_eq!(date(2024, 7, 31).to_string(), "2024-07-31");
19assert_eq!(time(15, 20, 0, 123).to_string(), "15:20:00.000000123");
20assert_eq!(
21    date(2024, 7, 31).at(15, 20, 0, 123).to_string(),
22    "2024-07-31T15:20:00.000000123",
23);
24assert_eq!(
25    time(15, 20, 0, 123).on(2024, 7, 31).to_string(),
26    "2024-07-31T15:20:00.000000123",
27);
28```
29
30# What is "civil" time?
31
32A civil datetime is a calendar date and a clock time. It also goes by the names
33"naive," "local" or "plain." The most important thing to understand about civil
34time is that it does not correspond to a precise instant in time. This is in
35contrast to types like [`Timestamp`](crate::Timestamp) and
36[`ZonedDateTime`](crate::ZonedDateTime), which _do_ correspond to a precise
37instant in time (to nanosecond precision).
38
39Because a civil datetime _never_ has a time zone associated with it, and
40because some time zones have transitions that skip or repeat clock times, it
41follows that not all civil datetimes precisely map to a single instant in time.
42For example, `2024-03-10 02:30` never existed on a clock in `America/New_York`
43because the 2 o'clock hour was skipped when the clocks were "moved forward"
44for daylight saving time. Conversely, `2024-11-03 01:30` occurred twice in
45`America/New_York` because the 1 o'clock hour was repeated when clocks were
46"moved backward" for daylight saving time. (When time is skipped, it's called a
47"gap." When time is repeated, it's called a "fold.")
48
49In contrast, an instant in time (that is, `Timestamp` or `ZonedDateTime`) can
50_always_ be converted to a civil datetime. And, when a civil datetime is
51combined with its time zone identifier _and_ its offset, the resulting machine
52readable string is unambiguous 100% of the time:
53
54```
55use jiff::{civil::date, tz::TimeZone};
56
57let tz = TimeZone::get("America/New_York")?;
58let dt = date(2024, 11, 3).at(1, 30, 0, 0);
59// It's ambiguous, so asking for an unambiguous instant presents an error!
60assert!(tz.to_ambiguous_zoned_datetime(dt).unambiguous().is_err());
61// Gives you the earlier time in a fold, i.e., before DST ends:
62assert_eq!(
63    tz.to_ambiguous_zoned_datetime(dt).earlier()?.to_string(),
64    "2024-11-03T01:30:00-04:00[America/New_York]",
65);
66// Gives you the later time in a fold, i.e., after DST ends.
67// Notice the offset change from the previous example!
68assert_eq!(
69    tz.to_ambiguous_zoned_datetime(dt).later()?.to_string(),
70    "2024-11-03T01:30:00-05:00[America/New_York]",
71);
72// "Just give me something reasonable"
73assert_eq!(
74    tz.to_ambiguous_zoned_datetime(dt).compatible()?.to_string(),
75    "2024-11-03T01:30:00-04:00[America/New_York]",
76);
77
78# Ok::<(), Box<dyn std::error::Error>>(())
79```
80
81# When should I use civil time?
82
83Here is a likely non-exhaustive list of reasons why you might want to use
84civil time:
85
86* When you want or need to deal with calendar and clock units as an
87intermediate step before and/or after associating it with a time zone. For
88example, perhaps you need to parse strings like `2000-01-01T00:00:00` from a
89CSV file that have no time zone or offset information, but the time zone is
90implied through some out-of-band mechanism.
91* When time zone is actually irrelevant. For example, a fitness tracking app
92that reminds you to work-out at 6am local time, regardless of which time zone
93you're in.
94* When you need to perform arithmetic that deliberately ignores daylight
95saving time.
96* When interacting with legacy systems or systems that specifically do not
97support time zones.
98
99# What about dates preceding the introduction of the Gregorian calendar?
100
101Jiff uses what is called the _proleptic_ Gregorian calendar. This means that
102Jiff behaves _as if_ the Gregorian calendar has been used for all of time.
103
104In reality, the Gregorian calendar wasn't introduced until October 1582.
105However, not all places in the world adopted the Gregorian calendar at that
106time. For example, Russia didn't convert from the Julian calendar to the
107Gregorian calendar until 1917.
108
109By using the proleptic calendar---where by we pretend the Gregorian calendar
110has always been in use---we are sacrificing contextually and historically
111accurate dates in favor of a massive simplification in datetime handling. In
112general, the process of determining the correct calendar used by a given locale
113and at a given time is a research task that is outside the scope of what Jiff
114offers.
115*/
116
117pub use self::{
118    date::{Date, DateArithmetic, DateDifference, DateSeries, DateWith},
119    datetime::{
120        DateTime, DateTimeArithmetic, DateTimeDifference, DateTimeRound,
121        DateTimeSeries, DateTimeWith,
122    },
123    iso_week_date::ISOWeekDate,
124    time::{
125        Time, TimeArithmetic, TimeDifference, TimeRound, TimeSeries, TimeWith,
126    },
127    weekday::{Weekday, WeekdaysForward, WeekdaysReverse},
128};
129
130mod date;
131mod datetime;
132mod iso_week_date;
133mod time;
134mod weekday;
135
136/// The era corresponding to a particular year.
137///
138/// The BCE era corresponds to years less than or equal to `0`, while the CE
139/// era corresponds to years greater than `0`.
140///
141/// In particular, this crate allows years to be negative and also to be `0`,
142/// which is contrary to the common practice of excluding the year `0` when
143/// writing dates for the Gregorian calendar. Moreover, common practice eschews
144/// negative years in favor of labeling a year with an era notation. That is,
145/// the year `1 BCE` is year `0` in this crate. The year `2 BCE` is the year
146/// `-1` in this crate.
147///
148/// To get the year in its era format, use [`Date::era_year`].
149#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Era {
}
#[automatically_derived]impl ::core::clone::Clone for Era {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Era { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Era {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { Era::BCE => "BCE", Era::CE => "CE", })
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for Era { }Eq, #[automatically_derived]impl ::core::hash::Hash for Era {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Era { }
#[automatically_derived]impl ::core::cmp::PartialEq for Era {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
150#[cfg_attr(feature = "defmt", derive(defmt::Format))]
151pub enum Era {
152    /// The "before common era" era.
153    ///
154    /// This corresponds to all years less than or equal to `0`.
155    ///
156    /// This is precisely equivalent to the "BC" or "before Christ" era.
157    BCE,
158    /// The "common era" era.
159    ///
160    /// This corresponds to all years greater than `0`.
161    ///
162    /// This is precisely equivalent to the "AD" or "anno Domini" or "in the
163    /// year of the Lord" era.
164    CE,
165}
166
167/// Creates a new `DateTime` value in a `const` context.
168///
169/// This is a convenience free function for [`DateTime::constant`]. It is
170/// intended to provide a terse syntax for constructing `DateTime` values from
171/// parameters that are known to be valid.
172///
173/// # Panics
174///
175/// This routine panics when [`DateTime::new`] would return an error. That
176/// is, when the given components do not correspond to a valid datetime.
177/// Namely, all of the following must be true:
178///
179/// * The year must be in the range `-9999..=9999`.
180/// * The month must be in the range `1..=12`.
181/// * The day must be at least `1` and must be at most the number of days
182/// in the corresponding month. So for example, `2024-02-29` is valid but
183/// `2023-02-29` is not.
184/// * `0 <= hour <= 23`
185/// * `0 <= minute <= 59`
186/// * `0 <= second <= 59`
187/// * `0 <= subsec_nanosecond <= 999,999,999`
188///
189/// Similarly, when used in a const context, invalid parameters will prevent
190/// your Rust program from compiling.
191///
192/// # Example
193///
194/// ```
195/// use jiff::civil::datetime;
196///
197/// let dt = datetime(2024, 2, 29, 21, 30, 5, 123_456_789);
198/// assert_eq!(dt.date().year(), 2024);
199/// assert_eq!(dt.date().month(), 2);
200/// assert_eq!(dt.date().day(), 29);
201/// assert_eq!(dt.time().hour(), 21);
202/// assert_eq!(dt.time().minute(), 30);
203/// assert_eq!(dt.time().second(), 5);
204/// assert_eq!(dt.time().millisecond(), 123);
205/// assert_eq!(dt.time().microsecond(), 456);
206/// assert_eq!(dt.time().nanosecond(), 789);
207/// ```
208#[inline]
209pub const fn datetime(
210    year: i16,
211    month: i8,
212    day: i8,
213    hour: i8,
214    minute: i8,
215    second: i8,
216    subsec_nanosecond: i32,
217) -> DateTime {
218    DateTime::constant(
219        year,
220        month,
221        day,
222        hour,
223        minute,
224        second,
225        subsec_nanosecond,
226    )
227}
228
229/// Creates a new `Date` value in a `const` context.
230///
231/// This is a convenience free function for [`Date::constant`]. It is intended
232/// to provide a terse syntax for constructing `Date` values from parameters
233/// that are known to be valid.
234///
235/// # Panics
236///
237/// This routine panics when [`Date::new`] would return an error. That is,
238/// when the given year-month-day does not correspond to a valid date.
239/// Namely, all of the following must be true:
240///
241/// * The year must be in the range `-9999..=9999`.
242/// * The month must be in the range `1..=12`.
243/// * The day must be at least `1` and must be at most the number of days
244/// in the corresponding month. So for example, `2024-02-29` is valid but
245/// `2023-02-29` is not.
246///
247/// Similarly, when used in a const context, invalid parameters will prevent
248/// your Rust program from compiling.
249///
250/// # Example
251///
252/// ```
253/// use jiff::civil::date;
254///
255/// let d = date(2024, 2, 29);
256/// assert_eq!(d.year(), 2024);
257/// assert_eq!(d.month(), 2);
258/// assert_eq!(d.day(), 29);
259/// ```
260#[inline]
261pub const fn date(year: i16, month: i8, day: i8) -> Date {
262    Date::constant(year, month, day)
263}
264
265/// Creates a new `Time` value in a `const` context.
266///
267/// This is a convenience free function for [`Time::constant`]. It is intended
268/// to provide a terse syntax for constructing `Time` values from parameters
269/// that are known to be valid.
270///
271/// # Panics
272///
273/// This panics if the given values do not correspond to a valid `Time`.
274/// All of the following conditions must be true:
275///
276/// * `0 <= hour <= 23`
277/// * `0 <= minute <= 59`
278/// * `0 <= second <= 59`
279/// * `0 <= subsec_nanosecond <= 999,999,999`
280///
281/// Similarly, when used in a const context, invalid parameters will
282/// prevent your Rust program from compiling.
283///
284/// # Example
285///
286/// This shows an example of a valid time in a `const` context:
287///
288/// ```
289/// use jiff::civil::time;
290///
291/// let t = time(21, 30, 5, 123_456_789);
292/// assert_eq!(t.hour(), 21);
293/// assert_eq!(t.minute(), 30);
294/// assert_eq!(t.second(), 5);
295/// assert_eq!(t.millisecond(), 123);
296/// assert_eq!(t.microsecond(), 456);
297/// assert_eq!(t.nanosecond(), 789);
298/// assert_eq!(t.subsec_nanosecond(), 123_456_789);
299/// ```
300#[inline]
301pub const fn time(
302    hour: i8,
303    minute: i8,
304    second: i8,
305    subsec_nanosecond: i32,
306) -> Time {
307    Time::constant(hour, minute, second, subsec_nanosecond)
308}