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