1 // This is a part of Chrono.
2 // See README.md and LICENSE.txt for details.
4 //! Formatting (and parsing) utilities for date and time.
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.
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 [one built-in syntax closely resembling
16 //! C's `strftime` format](./strftime/index.html).
19 use std
::str::FromStr
;
20 use std
::error
::Error
;
22 use {Datelike, Timelike, Weekday, ParseWeekdayError}
;
23 use div
::{div_floor, mod_floor}
;
24 use offset
::{Offset, FixedOffset}
;
25 use naive
::{NaiveDate, NaiveTime}
;
27 pub use self::strftime
::StrftimeItems
;
28 pub use self::parsed
::Parsed
;
29 pub use self::parse
::parse
;
31 /// An unhabitated type used for `InternalNumeric` and `InternalFixed` below.
32 #[derive(Clone, PartialEq, Eq)]
35 /// Padding characters for numeric items.
36 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
40 /// Zero (`0`) padding.
46 /// Numeric item types.
47 /// They have associated formatting width (FW) and parsing width (PW).
49 /// The **formatting width** is the minimal width to be formatted.
50 /// If the number is too short, and the padding is not [`Pad::None`](./enum.Pad.html#variant.None),
51 /// then it is left-padded.
52 /// If the number is too long or (in some cases) negative, it is printed as is.
54 /// The **parsing width** is the maximal width to be scanned.
55 /// The parser only tries to consume from one to given number of digits (greedily).
56 /// It also trims the preceding whitespaces if any.
57 /// It cannot parse the negative number, so some date and time cannot be formatted then
58 /// parsed with the same formatting items.
59 #[derive(Clone, PartialEq, Eq, Debug)]
61 /// Full Gregorian year (FW=4, PW=∞).
62 /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
64 /// Gregorian year divided by 100 (century number; FW=PW=2). Implies the non-negative year.
66 /// Gregorian year modulo 100 (FW=PW=2). Cannot be negative.
68 /// Year in the ISO week date (FW=4, PW=∞).
69 /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
71 /// Year in the ISO week date, divided by 100 (FW=PW=2). Implies the non-negative year.
73 /// Year in the ISO week date, modulo 100 (FW=PW=2). Cannot be negative.
77 /// Day of the month (FW=PW=2).
79 /// Week number, where the week 1 starts at the first Sunday of January (FW=PW=2).
81 /// Week number, where the week 1 starts at the first Monday of January (FW=PW=2).
83 /// Week number in the ISO week date (FW=PW=2).
85 /// Day of the week, where Sunday = 0 and Saturday = 6 (FW=PW=1).
87 /// Day of the week, where Monday = 1 and Sunday = 7 (FW=PW=1).
89 /// Day of the year (FW=PW=3).
91 /// Hour number in the 24-hour clocks (FW=PW=2).
93 /// Hour number in the 12-hour clocks (FW=PW=2).
95 /// The number of minutes since the last whole hour (FW=PW=2).
97 /// The number of seconds since the last whole minute (FW=PW=2).
99 /// The number of nanoseconds since the last whole second (FW=PW=9).
100 /// Note that this is *not* left-aligned;
101 /// see also [`Fixed::Nanosecond`](./enum.Fixed.html#variant.Nanosecond).
103 /// The number of non-leap seconds since the midnight UTC on January 1, 1970 (FW=1, PW=∞).
104 /// For formatting, it assumes UTC upon the absence of time zone offset.
107 /// Internal uses only.
109 /// This item exists so that one can add additional internal-only formatting
110 /// without breaking major compatibility (as enum variants cannot be selectively private).
111 Internal(InternalNumeric
),
114 /// An opaque type representing numeric item types for internal uses only.
115 pub struct InternalNumeric
{
119 impl Clone
for InternalNumeric
{
120 fn clone(&self) -> Self {
125 impl PartialEq
for InternalNumeric
{
126 fn eq(&self, _other
: &InternalNumeric
) -> bool
{
131 impl Eq
for InternalNumeric
{
134 impl fmt
::Debug
for InternalNumeric
{
135 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
136 write
!(f
, "<InternalNumeric>")
140 /// Fixed-format item types.
142 /// They have their own rules of formatting and parsing.
143 /// Otherwise noted, they print in the specified cases but parse case-insensitively.
144 #[derive(Clone, PartialEq, Eq, Debug)]
146 /// Abbreviated month names.
148 /// Prints a three-letter-long name in the title case, reads the same name in any case.
150 /// Full month names.
152 /// Prints a full name in the title case, reads either a short or full name in any case.
154 /// Abbreviated day of the week names.
156 /// Prints a three-letter-long name in the title case, reads the same name in any case.
158 /// Full day of the week names.
160 /// Prints a full name in the title case, reads either a short or full name in any case.
164 /// Prints in lower case, reads in any case.
168 /// Prints in upper case, reads in any case.
170 /// An optional dot plus one or more digits for left-aligned nanoseconds.
171 /// May print nothing, 3, 6 or 9 digits according to the available accuracy.
172 /// See also [`Numeric::Nanosecond`](./enum.Numeric.html#variant.Nanosecond).
174 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3.
176 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6.
178 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9.
182 /// It does not support parsing, its use in the parser is an immediate failure.
184 /// Offset from the local time to UTC (`+09:00` or `-04:00` or `+00:00`).
186 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespaces.
187 /// The offset is limited from `-24:00` to `+24:00`,
188 /// which is same to [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
190 /// Offset from the local time to UTC (`+09:00` or `-04:00` or `Z`).
192 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespaces,
193 /// and `Z` can be either in upper case or in lower case.
194 /// The offset is limited from `-24:00` to `+24:00`,
195 /// which is same to [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
196 TimezoneOffsetColonZ
,
197 /// Same to [`TimezoneOffsetColon`](#variant.TimezoneOffsetColon) but prints no colon.
198 /// Parsing allows an optional colon.
200 /// Same to [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ) but prints no colon.
201 /// Parsing allows an optional colon.
203 /// RFC 2822 date and time syntax. Commonly used for email and MIME date and time.
205 /// RFC 3339 & ISO 8601 date and time syntax.
208 /// Internal uses only.
210 /// This item exists so that one can add additional internal-only formatting
211 /// without breaking major compatibility (as enum variants cannot be selectively private).
212 Internal(InternalFixed
),
215 /// An opaque type representing fixed-format item types for internal uses only.
216 pub struct InternalFixed
{
220 impl Clone
for InternalFixed
{
221 fn clone(&self) -> Self {
226 impl PartialEq
for InternalFixed
{
227 fn eq(&self, _other
: &InternalFixed
) -> bool
{
232 impl Eq
for InternalFixed
{
235 impl fmt
::Debug
for InternalFixed
{
236 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
237 write
!(f
, "<InternalFixed>")
241 /// A single formatting item. This is used for both formatting and parsing.
242 #[derive(Clone, PartialEq, Eq, Debug)]
244 /// A literally printed and parsed text.
246 /// Same to `Literal` but with the string owned by the item.
247 OwnedLiteral(Box
<str>),
248 /// Whitespace. Prints literally but reads zero or more whitespace.
250 /// Same to `Space` but with the string owned by the item.
251 OwnedSpace(Box
<str>),
252 /// Numeric item. Can be optionally padded to the maximal length (if any) when formatting;
253 /// the parser simply ignores any padded whitespace and zeroes.
254 Numeric(Numeric
, Pad
),
255 /// Fixed-format item.
257 /// Issues a formatting error. Used to signal an invalid format string.
261 macro_rules
! lit { ($x:expr) => (Item::Literal($x)) }
262 macro_rules
! sp { ($x:expr) => (Item::Space($x)) }
263 macro_rules
! num { ($x:ident) => (Item::Numeric(Numeric::$x, Pad::None)) }
264 macro_rules
! num0 { ($x:ident) => (Item::Numeric(Numeric::$x, Pad::Zero)) }
265 macro_rules
! nums { ($x:ident) => (Item::Numeric(Numeric::$x, Pad::Space)) }
266 macro_rules
! fix { ($x:ident) => (Item::Fixed(Fixed::$x)) }
268 /// An error from the `parse` function.
269 #[derive(Debug, Clone, PartialEq, Eq, Copy)]
270 pub struct ParseError(ParseErrorKind
);
272 // clippy false positive https://github.com/rust-lang-nursery/rust-clippy/issues/2475
273 #[cfg_attr(feature = "cargo-clippy", allow(empty_line_after_outer_attr))]
274 #[derive(Debug, Clone, PartialEq, Eq, Copy)]
275 enum ParseErrorKind
{
276 /// Given field is out of permitted range.
279 /// There is no possible date and time value with given set of fields.
281 /// This does not include the out-of-range conditions, which are trivially invalid.
282 /// It includes the case that there are one or more fields that are inconsistent to each other.
285 /// Given set of fields is not enough to make a requested date and time value.
287 /// Note that there *may* be a case that given fields constrain the possible values so much
288 /// that there is a unique possible value. Chrono only tries to be correct for
289 /// most useful sets of fields however, as such constraint solving can be expensive.
292 /// The input string has some invalid character sequence for given formatting items.
295 /// The input string has been prematurely ended.
298 /// All formatting items have been read but there is a remaining input.
301 /// There was an error on the formatting string, or there were non-supported formating items.
305 /// Same to `Result<T, ParseError>`.
306 pub type ParseResult
<T
> = Result
<T
, ParseError
>;
308 impl fmt
::Display
for ParseError
{
309 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
310 self.description().fmt(f
)
314 impl Error
for ParseError
{
315 fn description(&self) -> &str {
317 ParseErrorKind
::OutOfRange
=> "input is out of range",
318 ParseErrorKind
::Impossible
=> "no possible date and time matching input",
319 ParseErrorKind
::NotEnough
=> "input is not enough for unique date and time",
320 ParseErrorKind
::Invalid
=> "input contains invalid characters",
321 ParseErrorKind
::TooShort
=> "premature end of input",
322 ParseErrorKind
::TooLong
=> "trailing input",
323 ParseErrorKind
::BadFormat
=> "bad or unsupported format string",
328 // to be used in this module and submodules
329 const OUT_OF_RANGE
: ParseError
= ParseError(ParseErrorKind
::OutOfRange
);
330 const IMPOSSIBLE
: ParseError
= ParseError(ParseErrorKind
::Impossible
);
331 const NOT_ENOUGH
: ParseError
= ParseError(ParseErrorKind
::NotEnough
);
332 const INVALID
: ParseError
= ParseError(ParseErrorKind
::Invalid
);
333 const TOO_SHORT
: ParseError
= ParseError(ParseErrorKind
::TooShort
);
334 const TOO_LONG
: ParseError
= ParseError(ParseErrorKind
::TooLong
);
335 const BAD_FORMAT
: ParseError
= ParseError(ParseErrorKind
::BadFormat
);
337 /// Tries to format given arguments with given formatting items.
338 /// Internally used by `DelayedFormat`.
339 pub fn format
<'a
, I
>(w
: &mut fmt
::Formatter
, date
: Option
<&NaiveDate
>, time
: Option
<&NaiveTime
>,
340 off
: Option
<&(String
, FixedOffset
)>, items
: I
) -> fmt
::Result
341 where I
: Iterator
<Item
=Item
<'a
>> {
342 // full and abbreviated month and weekday names
343 static SHORT_MONTHS
: [&'
static str; 12] =
344 ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
345 static LONG_MONTHS
: [&'
static str; 12] =
346 ["January", "February", "March", "April", "May", "June",
347 "July", "August", "September", "October", "November", "December"];
348 static SHORT_WEEKDAYS
: [&'
static str; 7] =
349 ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
350 static LONG_WEEKDAYS
: [&'
static str; 7] =
351 ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
355 Item
::Literal(s
) | Item
::Space(s
) => try
!(write
!(w
, "{}", s
)),
356 Item
::OwnedLiteral(ref s
) | Item
::OwnedSpace(ref s
) => try
!(write
!(w
, "{}", s
)),
358 Item
::Numeric(spec
, pad
) => {
359 use self::Numeric
::*;
361 let week_from_sun
= |d
: &NaiveDate
|
362 (d
.ordinal() as i32 - d
.weekday().num_days_from_sunday() as i32 + 7) / 7;
363 let week_from_mon
= |d
: &NaiveDate
|
364 (d
.ordinal() as i32 - d
.weekday().num_days_from_monday() as i32 + 7) / 7;
366 let (width
, v
) = match spec
{
367 Year
=> (4, date
.map(|d
| i64::from(d
.year()))),
368 YearDiv100
=> (2, date
.map(|d
| div_floor(i64::from(d
.year()), 100))),
369 YearMod100
=> (2, date
.map(|d
| mod_floor(i64::from(d
.year()), 100))),
370 IsoYear
=> (4, date
.map(|d
| i64::from(d
.iso_week().year()))),
371 IsoYearDiv100
=> (2, date
.map(|d
| div_floor(
372 i64::from(d
.iso_week().year()), 100))),
373 IsoYearMod100
=> (2, date
.map(|d
| mod_floor(
374 i64::from(d
.iso_week().year()), 100))),
375 Month
=> (2, date
.map(|d
| i64::from(d
.month()))),
376 Day
=> (2, date
.map(|d
| i64::from(d
.day()))),
377 WeekFromSun
=> (2, date
.map(|d
| i64::from(week_from_sun(d
)))),
378 WeekFromMon
=> (2, date
.map(|d
| i64::from(week_from_mon(d
)))),
379 IsoWeek
=> (2, date
.map(|d
| i64::from(d
.iso_week().week()))),
380 NumDaysFromSun
=> (1, date
.map(|d
| i64::from(d
.weekday()
381 .num_days_from_sunday()))),
382 WeekdayFromMon
=> (1, date
.map(|d
| i64::from(d
.weekday()
383 .number_from_monday()))),
384 Ordinal
=> (3, date
.map(|d
| i64::from(d
.ordinal()))),
385 Hour
=> (2, time
.map(|t
| i64::from(t
.hour()))),
386 Hour12
=> (2, time
.map(|t
| i64::from(t
.hour12().1))),
387 Minute
=> (2, time
.map(|t
| i64::from(t
.minute()))),
388 Second
=> (2, time
.map(|t
| i64::from(t
.second() +
389 t
.nanosecond() / 1_000_000_000))),
390 Nanosecond
=> (9, time
.map(|t
| i64::from(t
.nanosecond() % 1_000_000_000))),
391 Timestamp
=> (1, match (date
, time
, off
) {
392 (Some(d
), Some(t
), None
) =>
393 Some(d
.and_time(*t
).timestamp()),
394 (Some(d
), Some(t
), Some(&(_
, off
))) =>
395 Some((d
.and_time(*t
) - off
).timestamp()),
399 // for the future expansion
400 Internal(ref int
) => match int
._dummy {}
,
404 if (spec
== Year
|| spec
== IsoYear
) && !(0 <= v
&& v
< 10_000) {
405 // non-four-digit years require an explicit sign as per ISO 8601
407 Pad
::None
=> try
!(write
!(w
, "{:+}", v
)),
408 Pad
::Zero
=> try
!(write
!(w
, "{:+01$}", v
, width
+ 1)),
409 Pad
::Space
=> try
!(write
!(w
, "{:+1$}", v
, width
+ 1)),
413 Pad
::None
=> try
!(write
!(w
, "{}", v
)),
414 Pad
::Zero
=> try
!(write
!(w
, "{:01$}", v
, width
)),
415 Pad
::Space
=> try
!(write
!(w
, "{:1$}", v
, width
)),
419 return Err(fmt
::Error
); // insufficient arguments for given format
423 Item
::Fixed(spec
) => {
426 /// Prints an offset from UTC in the format of `+HHMM` or `+HH:MM`.
427 /// `Z` instead of `+00[:]00` is allowed when `allow_zulu` is true.
428 fn write_local_minus_utc(w
: &mut fmt
::Formatter
, off
: FixedOffset
,
429 allow_zulu
: bool
, use_colon
: bool
) -> fmt
::Result
{
430 let off
= off
.local_minus_utc();
431 if !allow_zulu
|| off
!= 0 {
432 let (sign
, off
) = if off
< 0 {('-', -off)}
else {('+', off)}
;
434 write
!(w
, "{}{:02}:{:02}", sign
, off
/ 3600, off
/ 60 % 60)
436 write
!(w
, "{}{:02}{:02}", sign
, off
/ 3600, off
/ 60 % 60)
443 let ret
= match spec
{
445 date
.map(|d
| write
!(w
, "{}", SHORT_MONTHS
[d
.month0() as usize])),
447 date
.map(|d
| write
!(w
, "{}", LONG_MONTHS
[d
.month0() as usize])),
449 date
.map(|d
| write
!(w
, "{}",
450 SHORT_WEEKDAYS
[d
.weekday().num_days_from_monday() as usize])),
452 date
.map(|d
| write
!(w
, "{}",
453 LONG_WEEKDAYS
[d
.weekday().num_days_from_monday() as usize])),
455 time
.map(|t
| write
!(w
, "{}", if t
.hour12().0 {"pm"}
else {"am"}
)),
457 time
.map(|t
| write
!(w
, "{}", if t
.hour12().0 {"PM"}
else {"AM"}
)),
460 let nano
= t
.nanosecond() % 1_000_000_000;
463 } else if nano
% 1_000_000 == 0 {
464 write
!(w
, ".{:03}", nano
/ 1_000_000)
465 } else if nano
% 1_000 == 0 {
466 write
!(w
, ".{:06}", nano
/ 1_000)
468 write
!(w
, ".{:09}", nano
)
473 let nano
= t
.nanosecond() % 1_000_000_000;
474 write
!(w
, ".{:03}", nano
/ 1_000_000)
478 let nano
= t
.nanosecond() % 1_000_000_000;
479 write
!(w
, ".{:06}", nano
/ 1_000)
483 let nano
= t
.nanosecond() % 1_000_000_000;
484 write
!(w
, ".{:09}", nano
)
487 off
.map(|&(ref name
, _
)| write
!(w
, "{}", *name
)),
488 TimezoneOffsetColon
=>
489 off
.map(|&(_
, off
)| write_local_minus_utc(w
, off
, false, true)),
490 TimezoneOffsetColonZ
=>
491 off
.map(|&(_
, off
)| write_local_minus_utc(w
, off
, true, true)),
493 off
.map(|&(_
, off
)| write_local_minus_utc(w
, off
, false, false)),
495 off
.map(|&(_
, off
)| write_local_minus_utc(w
, off
, true, false)),
496 RFC2822
=> // same to `%a, %e %b %Y %H:%M:%S %z`
497 if let (Some(d
), Some(t
), Some(&(_
, off
))) = (date
, time
, off
) {
498 let sec
= t
.second() + t
.nanosecond() / 1_000_000_000;
499 try
!(write
!(w
, "{}, {:2} {} {:04} {:02}:{:02}:{:02} ",
500 SHORT_WEEKDAYS
[d
.weekday().num_days_from_monday() as usize],
501 d
.day(), SHORT_MONTHS
[d
.month0() as usize], d
.year(),
502 t
.hour(), t
.minute(), sec
));
503 Some(write_local_minus_utc(w
, off
, false, false))
507 RFC3339
=> // same to `%Y-%m-%dT%H:%M:%S%.f%:z`
508 if let (Some(d
), Some(t
), Some(&(_
, off
))) = (date
, time
, off
) {
509 // reuse `Debug` impls which already print ISO 8601 format.
510 // this is faster in this way.
511 try
!(write
!(w
, "{:?}T{:?}", d
, t
));
512 Some(write_local_minus_utc(w
, off
, false, true))
517 // for the future expansion
518 Internal(ref int
) => match int
._dummy {}
,
522 Some(ret
) => try
!(ret
),
523 None
=> return Err(fmt
::Error
), // insufficient arguments for given format
527 Item
::Error
=> return Err(fmt
::Error
),
536 // due to the size of parsing routines, they are in separate modules.
542 /// A *temporary* object which can be used as an argument to `format!` or others.
543 /// This is normally constructed via `format` methods of each date and time type.
545 pub struct DelayedFormat
<I
> {
546 /// The date view, if any.
547 date
: Option
<NaiveDate
>,
548 /// The time view, if any.
549 time
: Option
<NaiveTime
>,
550 /// The name and local-to-UTC difference for the offset (timezone), if any.
551 off
: Option
<(String
, FixedOffset
)>,
552 /// An iterator returning formatting items.
556 impl<'a
, I
: Iterator
<Item
=Item
<'a
>> + Clone
> DelayedFormat
<I
> {
557 /// Makes a new `DelayedFormat` value out of local date and time.
558 pub fn new(date
: Option
<NaiveDate
>, time
: Option
<NaiveTime
>, items
: I
) -> DelayedFormat
<I
> {
559 DelayedFormat { date: date, time: time, off: None, items: items }
562 /// Makes a new `DelayedFormat` value out of local date and time and UTC offset.
563 pub fn new_with_offset
<Off
>(date
: Option
<NaiveDate
>, time
: Option
<NaiveTime
>,
564 offset
: &Off
, items
: I
) -> DelayedFormat
<I
>
565 where Off
: Offset
+ fmt
::Display
{
566 let name_and_diff
= (offset
.to_string(), offset
.fix());
567 DelayedFormat { date: date, time: time, off: Some(name_and_diff), items: items }
571 impl<'a
, I
: Iterator
<Item
=Item
<'a
>> + Clone
> fmt
::Display
for DelayedFormat
<I
> {
572 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
573 format(f
, self.date
.as_ref(), self.time
.as_ref(), self.off
.as_ref(), self.items
.clone())
577 // this implementation is here only because we need some private code from `scan`
579 /// Parsing a `str` into a `Weekday` uses the format [`%W`](./format/strftime/index.html).
584 /// use chrono::Weekday;
586 /// assert_eq!("Sunday".parse::<Weekday>(), Ok(Weekday::Sun));
587 /// assert!("any day".parse::<Weekday>().is_err());
590 /// The parsing is case-insensitive.
593 /// # use chrono::Weekday;
594 /// assert_eq!("mON".parse::<Weekday>(), Ok(Weekday::Mon));
597 /// Only the shortest form (e.g. `sun`) and the longest form (e.g. `sunday`) is accepted.
600 /// # use chrono::Weekday;
601 /// assert!("thurs".parse::<Weekday>().is_err());
603 impl FromStr
for Weekday
{
604 type Err
= ParseWeekdayError
;
606 fn from_str(s
: &str) -> Result
<Self, Self::Err
> {
607 if let Ok(("", w
)) = scan
::short_or_long_weekday(s
) {
610 Err(ParseWeekdayError { _dummy: () }
)