chrono/format/
mod.rs

1// This is a part of Chrono.
2// See README.md and LICENSE.txt for details.
3
4//! Formatting (and parsing) utilities for date and time.
5//!
6//! This module provides the common types and routines to implement,
7//! for example, [`DateTime::format`](../struct.DateTime.html#method.format) or
8//! [`DateTime::parse_from_str`](../struct.DateTime.html#method.parse_from_str) methods.
9//! For most cases you should use these high-level interfaces.
10//!
11//! Internally the formatting and parsing shares the same abstract **formatting items**,
12//! which are just an [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) of
13//! the [`Item`](./enum.Item.html) type.
14//! They are generated from more readable **format strings**;
15//! currently Chrono supports a built-in syntax closely resembling
16//! C's `strftime` format. The available options can be found [here](./strftime/index.html).
17//!
18//! # Example
19//! ```
20//! # #[cfg(feature = "alloc")] {
21//! use chrono::{NaiveDateTime, TimeZone, Utc};
22//!
23//! let date_time = Utc.with_ymd_and_hms(2020, 11, 10, 0, 1, 32).unwrap();
24//!
25//! let formatted = format!("{}", date_time.format("%Y-%m-%d %H:%M:%S"));
26//! assert_eq!(formatted, "2020-11-10 00:01:32");
27//!
28//! let parsed = NaiveDateTime::parse_from_str(&formatted, "%Y-%m-%d %H:%M:%S")?.and_utc();
29//! assert_eq!(parsed, date_time);
30//! # }
31//! # Ok::<(), chrono::ParseError>(())
32//! ```
33
34#[cfg(all(feature = "alloc", not(feature = "std"), not(test)))]
35use alloc::boxed::Box;
36use core::fmt;
37use core::str::FromStr;
38#[cfg(feature = "std")]
39use std::error::Error;
40
41use crate::{Month, ParseMonthError, ParseWeekdayError, Weekday};
42
43mod formatting;
44mod parsed;
45
46// due to the size of parsing routines, they are in separate modules.
47mod parse;
48pub(crate) mod scan;
49
50pub mod strftime;
51
52#[allow(unused)]
53// TODO: remove '#[allow(unused)]' once we use this module for parsing or something else that does
54// not require `alloc`.
55pub(crate) mod locales;
56
57pub(crate) use formatting::write_hundreds;
58#[cfg(feature = "alloc")]
59pub(crate) use formatting::write_rfc2822;
60#[cfg(any(feature = "alloc", feature = "serde"))]
61pub(crate) use formatting::write_rfc3339;
62pub use formatting::SecondsFormat;
63#[cfg(feature = "alloc")]
64#[allow(deprecated)]
65pub use formatting::{format, format_item, DelayedFormat};
66#[cfg(feature = "unstable-locales")]
67pub use locales::Locale;
68pub(crate) use parse::parse_rfc3339;
69pub use parse::{parse, parse_and_remainder};
70pub use parsed::Parsed;
71pub use strftime::StrftimeItems;
72
73/// An uninhabited type used for `InternalNumeric` and `InternalFixed` below.
74#[derive(Clone, PartialEq, Eq, Hash)]
75enum Void {}
76
77/// Padding characters for numeric items.
78#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
79pub enum Pad {
80    /// No padding.
81    None,
82    /// Zero (`0`) padding.
83    Zero,
84    /// Space padding.
85    Space,
86}
87
88/// Numeric item types.
89/// They have associated formatting width (FW) and parsing width (PW).
90///
91/// The **formatting width** is the minimal width to be formatted.
92/// If the number is too short, and the padding is not [`Pad::None`](./enum.Pad.html#variant.None),
93/// then it is left-padded.
94/// If the number is too long or (in some cases) negative, it is printed as is.
95///
96/// The **parsing width** is the maximal width to be scanned.
97/// The parser only tries to consume from one to given number of digits (greedily).
98/// It also trims the preceding whitespace if any.
99/// It cannot parse the negative number, so some date and time cannot be formatted then
100/// parsed with the same formatting items.
101#[non_exhaustive]
102#[derive(Clone, PartialEq, Eq, Debug, Hash)]
103pub enum Numeric {
104    /// Full Gregorian year (FW=4, PW=∞).
105    /// May accept years before 1 BCE or after 9999 CE, given an initial sign (+/-).
106    Year,
107    /// Gregorian year divided by 100 (century number; FW=PW=2). Implies the non-negative year.
108    YearDiv100,
109    /// Gregorian year modulo 100 (FW=PW=2). Cannot be negative.
110    YearMod100,
111    /// Year in the ISO week date (FW=4, PW=∞).
112    /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
113    IsoYear,
114    /// Year in the ISO week date, divided by 100 (FW=PW=2). Implies the non-negative year.
115    IsoYearDiv100,
116    /// Year in the ISO week date, modulo 100 (FW=PW=2). Cannot be negative.
117    IsoYearMod100,
118    /// Month (FW=PW=2).
119    Month,
120    /// Day of the month (FW=PW=2).
121    Day,
122    /// Week number, where the week 1 starts at the first Sunday of January (FW=PW=2).
123    WeekFromSun,
124    /// Week number, where the week 1 starts at the first Monday of January (FW=PW=2).
125    WeekFromMon,
126    /// Week number in the ISO week date (FW=PW=2).
127    IsoWeek,
128    /// Day of the week, where Sunday = 0 and Saturday = 6 (FW=PW=1).
129    NumDaysFromSun,
130    /// Day of the week, where Monday = 1 and Sunday = 7 (FW=PW=1).
131    WeekdayFromMon,
132    /// Day of the year (FW=PW=3).
133    Ordinal,
134    /// Hour number in the 24-hour clocks (FW=PW=2).
135    Hour,
136    /// Hour number in the 12-hour clocks (FW=PW=2).
137    Hour12,
138    /// The number of minutes since the last whole hour (FW=PW=2).
139    Minute,
140    /// The number of seconds since the last whole minute (FW=PW=2).
141    Second,
142    /// The number of nanoseconds since the last whole second (FW=PW=9).
143    /// Note that this is *not* left-aligned;
144    /// see also [`Fixed::Nanosecond`](./enum.Fixed.html#variant.Nanosecond).
145    Nanosecond,
146    /// The number of non-leap seconds since the midnight UTC on January 1, 1970 (FW=1, PW=∞).
147    /// For formatting, it assumes UTC upon the absence of time zone offset.
148    Timestamp,
149
150    /// Internal uses only.
151    ///
152    /// This item exists so that one can add additional internal-only formatting
153    /// without breaking major compatibility (as enum variants cannot be selectively private).
154    Internal(InternalNumeric),
155}
156
157/// An opaque type representing numeric item types for internal uses only.
158#[derive(Clone, Eq, Hash, PartialEq)]
159pub struct InternalNumeric {
160    _dummy: Void,
161}
162
163impl fmt::Debug for InternalNumeric {
164    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165        write!(f, "<InternalNumeric>")
166    }
167}
168
169/// Fixed-format item types.
170///
171/// They have their own rules of formatting and parsing.
172/// Otherwise noted, they print in the specified cases but parse case-insensitively.
173#[non_exhaustive]
174#[derive(Clone, PartialEq, Eq, Debug, Hash)]
175pub enum Fixed {
176    /// Abbreviated month names.
177    ///
178    /// Prints a three-letter-long name in the title case, reads the same name in any case.
179    ShortMonthName,
180    /// Full month names.
181    ///
182    /// Prints a full name in the title case, reads either a short or full name in any case.
183    LongMonthName,
184    /// Abbreviated day of the week names.
185    ///
186    /// Prints a three-letter-long name in the title case, reads the same name in any case.
187    ShortWeekdayName,
188    /// Full day of the week names.
189    ///
190    /// Prints a full name in the title case, reads either a short or full name in any case.
191    LongWeekdayName,
192    /// AM/PM.
193    ///
194    /// Prints in lower case, reads in any case.
195    LowerAmPm,
196    /// AM/PM.
197    ///
198    /// Prints in upper case, reads in any case.
199    UpperAmPm,
200    /// An optional dot plus one or more digits for left-aligned nanoseconds.
201    /// May print nothing, 3, 6 or 9 digits according to the available accuracy.
202    /// See also [`Numeric::Nanosecond`](./enum.Numeric.html#variant.Nanosecond).
203    Nanosecond,
204    /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3.
205    Nanosecond3,
206    /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6.
207    Nanosecond6,
208    /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9.
209    Nanosecond9,
210    /// Timezone name.
211    ///
212    /// It does not support parsing, its use in the parser is an immediate failure.
213    TimezoneName,
214    /// Offset from the local time to UTC (`+09:00` or `-04:00` or `+00:00`).
215    ///
216    /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
217    /// The offset is limited from `-24:00` to `+24:00`,
218    /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
219    TimezoneOffsetColon,
220    /// Offset from the local time to UTC with seconds (`+09:00:00` or `-04:00:00` or `+00:00:00`).
221    ///
222    /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
223    /// The offset is limited from `-24:00:00` to `+24:00:00`,
224    /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
225    TimezoneOffsetDoubleColon,
226    /// Offset from the local time to UTC without minutes (`+09` or `-04` or `+00`).
227    ///
228    /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
229    /// The offset is limited from `-24` to `+24`,
230    /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
231    TimezoneOffsetTripleColon,
232    /// Offset from the local time to UTC (`+09:00` or `-04:00` or `Z`).
233    ///
234    /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace,
235    /// and `Z` can be either in upper case or in lower case.
236    /// The offset is limited from `-24:00` to `+24:00`,
237    /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
238    TimezoneOffsetColonZ,
239    /// Same as [`TimezoneOffsetColon`](#variant.TimezoneOffsetColon) but prints no colon.
240    /// Parsing allows an optional colon.
241    TimezoneOffset,
242    /// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ) but prints no colon.
243    /// Parsing allows an optional colon.
244    TimezoneOffsetZ,
245    /// RFC 2822 date and time syntax. Commonly used for email and MIME date and time.
246    RFC2822,
247    /// RFC 3339 & ISO 8601 date and time syntax.
248    RFC3339,
249
250    /// Internal uses only.
251    ///
252    /// This item exists so that one can add additional internal-only formatting
253    /// without breaking major compatibility (as enum variants cannot be selectively private).
254    Internal(InternalFixed),
255}
256
257/// An opaque type representing fixed-format item types for internal uses only.
258#[derive(Debug, Clone, PartialEq, Eq, Hash)]
259pub struct InternalFixed {
260    val: InternalInternal,
261}
262
263#[derive(Debug, Clone, PartialEq, Eq, Hash)]
264enum InternalInternal {
265    /// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ), but
266    /// allows missing minutes (per [ISO 8601][iso8601]).
267    ///
268    /// # Panics
269    ///
270    /// If you try to use this for printing.
271    ///
272    /// [iso8601]: https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC
273    TimezoneOffsetPermissive,
274    /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3 and there is no leading dot.
275    Nanosecond3NoDot,
276    /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6 and there is no leading dot.
277    Nanosecond6NoDot,
278    /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9 and there is no leading dot.
279    Nanosecond9NoDot,
280}
281
282/// Type for specifying the format of UTC offsets.
283#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
284pub struct OffsetFormat {
285    /// See `OffsetPrecision`.
286    pub precision: OffsetPrecision,
287    /// Separator between hours, minutes and seconds.
288    pub colons: Colons,
289    /// Represent `+00:00` as `Z`.
290    pub allow_zulu: bool,
291    /// Pad the hour value to two digits.
292    pub padding: Pad,
293}
294
295/// The precision of an offset from UTC formatting item.
296#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
297pub enum OffsetPrecision {
298    /// Format offset from UTC as only hours. Not recommended, it is not uncommon for timezones to
299    /// have an offset of 30 minutes, 15 minutes, etc.
300    /// Any minutes and seconds get truncated.
301    Hours,
302    /// Format offset from UTC as hours and minutes.
303    /// Any seconds will be rounded to the nearest minute.
304    Minutes,
305    /// Format offset from UTC as hours, minutes and seconds.
306    Seconds,
307    /// Format offset from UTC as hours, and optionally with minutes.
308    /// Any seconds will be rounded to the nearest minute.
309    OptionalMinutes,
310    /// Format offset from UTC as hours and minutes, and optionally seconds.
311    OptionalSeconds,
312    /// Format offset from UTC as hours and optionally minutes and seconds.
313    OptionalMinutesAndSeconds,
314}
315
316/// The separator between hours and minutes in an offset.
317#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
318pub enum Colons {
319    /// No separator
320    None,
321    /// Colon (`:`) as separator
322    Colon,
323    /// No separator when formatting, colon allowed when parsing.
324    Maybe,
325}
326
327/// A single formatting item. This is used for both formatting and parsing.
328#[derive(Clone, PartialEq, Eq, Debug, Hash)]
329pub enum Item<'a> {
330    /// A literally printed and parsed text.
331    Literal(&'a str),
332    /// Same as `Literal` but with the string owned by the item.
333    #[cfg(feature = "alloc")]
334    OwnedLiteral(Box<str>),
335    /// Whitespace. Prints literally but reads zero or more whitespace.
336    Space(&'a str),
337    /// Same as `Space` but with the string owned by the item.
338    #[cfg(feature = "alloc")]
339    OwnedSpace(Box<str>),
340    /// Numeric item. Can be optionally padded to the maximal length (if any) when formatting;
341    /// the parser simply ignores any padded whitespace and zeroes.
342    Numeric(Numeric, Pad),
343    /// Fixed-format item.
344    Fixed(Fixed),
345    /// Issues a formatting error. Used to signal an invalid format string.
346    Error,
347}
348
349const fn num(numeric: Numeric) -> Item<'static> {
350    Item::Numeric(numeric, Pad::None)
351}
352
353const fn num0(numeric: Numeric) -> Item<'static> {
354    Item::Numeric(numeric, Pad::Zero)
355}
356
357const fn nums(numeric: Numeric) -> Item<'static> {
358    Item::Numeric(numeric, Pad::Space)
359}
360
361const fn fixed(fixed: Fixed) -> Item<'static> {
362    Item::Fixed(fixed)
363}
364
365const fn internal_fixed(val: InternalInternal) -> Item<'static> {
366    Item::Fixed(Fixed::Internal(InternalFixed { val }))
367}
368
369impl Item<'_> {
370    /// Convert items that contain a reference to the format string into an owned variant.
371    #[cfg(any(feature = "alloc", feature = "std"))]
372    pub fn to_owned(self) -> Item<'static> {
373        match self {
374            Item::Literal(s) => Item::OwnedLiteral(Box::from(s)),
375            Item::Space(s) => Item::OwnedSpace(Box::from(s)),
376            Item::Numeric(n, p) => Item::Numeric(n, p),
377            Item::Fixed(f) => Item::Fixed(f),
378            Item::OwnedLiteral(l) => Item::OwnedLiteral(l),
379            Item::OwnedSpace(s) => Item::OwnedSpace(s),
380            Item::Error => Item::Error,
381        }
382    }
383}
384
385/// An error from the `parse` function.
386#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)]
387pub struct ParseError(ParseErrorKind);
388
389impl ParseError {
390    /// The category of parse error
391    pub const fn kind(&self) -> ParseErrorKind {
392        self.0
393    }
394}
395
396/// The category of parse error
397#[allow(clippy::manual_non_exhaustive)]
398#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)]
399pub enum ParseErrorKind {
400    /// Given field is out of permitted range.
401    OutOfRange,
402
403    /// There is no possible date and time value with given set of fields.
404    ///
405    /// This does not include the out-of-range conditions, which are trivially invalid.
406    /// It includes the case that there are one or more fields that are inconsistent to each other.
407    Impossible,
408
409    /// Given set of fields is not enough to make a requested date and time value.
410    ///
411    /// Note that there *may* be a case that given fields constrain the possible values so much
412    /// that there is a unique possible value. Chrono only tries to be correct for
413    /// most useful sets of fields however, as such constraint solving can be expensive.
414    NotEnough,
415
416    /// The input string has some invalid character sequence for given formatting items.
417    Invalid,
418
419    /// The input string has been prematurely ended.
420    TooShort,
421
422    /// All formatting items have been read but there is a remaining input.
423    TooLong,
424
425    /// There was an error on the formatting string, or there were non-supported formatting items.
426    BadFormat,
427
428    // TODO: Change this to `#[non_exhaustive]` (on the enum) with the next breaking release.
429    #[doc(hidden)]
430    __Nonexhaustive,
431}
432
433/// Same as `Result<T, ParseError>`.
434pub type ParseResult<T> = Result<T, ParseError>;
435
436impl fmt::Display for ParseError {
437    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
438        match self.0 {
439            ParseErrorKind::OutOfRange => write!(f, "input is out of range"),
440            ParseErrorKind::Impossible => write!(f, "no possible date and time matching input"),
441            ParseErrorKind::NotEnough => write!(f, "input is not enough for unique date and time"),
442            ParseErrorKind::Invalid => write!(f, "input contains invalid characters"),
443            ParseErrorKind::TooShort => write!(f, "premature end of input"),
444            ParseErrorKind::TooLong => write!(f, "trailing input"),
445            ParseErrorKind::BadFormat => write!(f, "bad or unsupported format string"),
446            _ => unreachable!(),
447        }
448    }
449}
450
451#[cfg(feature = "std")]
452impl Error for ParseError {
453    #[allow(deprecated)]
454    fn description(&self) -> &str {
455        "parser error, see to_string() for details"
456    }
457}
458
459// to be used in this module and submodules
460pub(crate) const OUT_OF_RANGE: ParseError = ParseError(ParseErrorKind::OutOfRange);
461const IMPOSSIBLE: ParseError = ParseError(ParseErrorKind::Impossible);
462const NOT_ENOUGH: ParseError = ParseError(ParseErrorKind::NotEnough);
463const INVALID: ParseError = ParseError(ParseErrorKind::Invalid);
464const TOO_SHORT: ParseError = ParseError(ParseErrorKind::TooShort);
465pub(crate) const TOO_LONG: ParseError = ParseError(ParseErrorKind::TooLong);
466const BAD_FORMAT: ParseError = ParseError(ParseErrorKind::BadFormat);
467
468// this implementation is here only because we need some private code from `scan`
469
470/// Parsing a `str` into a `Weekday` uses the format [`%A`](./format/strftime/index.html).
471///
472/// # Example
473///
474/// ```
475/// use chrono::Weekday;
476///
477/// assert_eq!("Sunday".parse::<Weekday>(), Ok(Weekday::Sun));
478/// assert!("any day".parse::<Weekday>().is_err());
479/// ```
480///
481/// The parsing is case-insensitive.
482///
483/// ```
484/// # use chrono::Weekday;
485/// assert_eq!("mON".parse::<Weekday>(), Ok(Weekday::Mon));
486/// ```
487///
488/// Only the shortest form (e.g. `sun`) and the longest form (e.g. `sunday`) is accepted.
489///
490/// ```
491/// # use chrono::Weekday;
492/// assert!("thurs".parse::<Weekday>().is_err());
493/// ```
494impl FromStr for Weekday {
495    type Err = ParseWeekdayError;
496
497    fn from_str(s: &str) -> Result<Self, Self::Err> {
498        if let Ok(("", w)) = scan::short_or_long_weekday(s) {
499            Ok(w)
500        } else {
501            Err(ParseWeekdayError { _dummy: () })
502        }
503    }
504}
505
506/// Parsing a `str` into a `Month` uses the format [`%B`](./format/strftime/index.html).
507///
508/// # Example
509///
510/// ```
511/// use chrono::Month;
512///
513/// assert_eq!("January".parse::<Month>(), Ok(Month::January));
514/// assert!("any day".parse::<Month>().is_err());
515/// ```
516///
517/// The parsing is case-insensitive.
518///
519/// ```
520/// # use chrono::Month;
521/// assert_eq!("fEbruARy".parse::<Month>(), Ok(Month::February));
522/// ```
523///
524/// Only the shortest form (e.g. `jan`) and the longest form (e.g. `january`) is accepted.
525///
526/// ```
527/// # use chrono::Month;
528/// assert!("septem".parse::<Month>().is_err());
529/// assert!("Augustin".parse::<Month>().is_err());
530/// ```
531impl FromStr for Month {
532    type Err = ParseMonthError;
533
534    fn from_str(s: &str) -> Result<Self, Self::Err> {
535        if let Ok(("", w)) = scan::short_or_long_month0(s) {
536            match w {
537                0 => Ok(Month::January),
538                1 => Ok(Month::February),
539                2 => Ok(Month::March),
540                3 => Ok(Month::April),
541                4 => Ok(Month::May),
542                5 => Ok(Month::June),
543                6 => Ok(Month::July),
544                7 => Ok(Month::August),
545                8 => Ok(Month::September),
546                9 => Ok(Month::October),
547                10 => Ok(Month::November),
548                11 => Ok(Month::December),
549                _ => Err(ParseMonthError { _dummy: () }),
550            }
551        } else {
552            Err(ParseMonthError { _dummy: () })
553        }
554    }
555}