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 [one built-in syntax closely resembling
16//! C's `strftime` format](./strftime/index.html).
17
18#![allow(ellipsis_inclusive_range_patterns)]
19
20use core::borrow::Borrow;
21use core::fmt;
22use core::str::FromStr;
23#[cfg(any(feature = "std", test))]
24use std::error::Error;
25#[cfg(feature = "alloc")]
26use alloc::boxed::Box;
27#[cfg(feature = "alloc")]
28use alloc::string::{String, ToString};
29
30#[cfg(any(feature = "alloc", feature = "std", test))]
31use {Datelike, Timelike};
32use {Weekday, ParseWeekdayError};
33#[cfg(any(feature = "alloc", feature = "std", test))]
34use div::{div_floor, mod_floor};
35#[cfg(any(feature = "alloc", feature = "std", test))]
36use offset::{Offset, FixedOffset};
37#[cfg(any(feature = "alloc", feature = "std", test))]
38use naive::{NaiveDate, NaiveTime};
39
40pub use self::strftime::StrftimeItems;
41pub use self::parsed::Parsed;
42pub use self::parse::parse;
43
44/// An uninhabited type used for `InternalNumeric` and `InternalFixed` below.
45#[derive(Clone, PartialEq, Eq)]
46enum Void {}
47
48/// Padding characters for numeric items.
49#[derive(Copy, Clone, PartialEq, Eq, Debug)]
50pub enum Pad {
51 /// No padding.
52 None,
53 /// Zero (`0`) padding.
54 Zero,
55 /// Space padding.
56 Space,
57}
58
59/// Numeric item types.
60/// They have associated formatting width (FW) and parsing width (PW).
61///
62/// The **formatting width** is the minimal width to be formatted.
63/// If the number is too short, and the padding is not [`Pad::None`](./enum.Pad.html#variant.None),
64/// then it is left-padded.
65/// If the number is too long or (in some cases) negative, it is printed as is.
66///
67/// The **parsing width** is the maximal width to be scanned.
68/// The parser only tries to consume from one to given number of digits (greedily).
69/// It also trims the preceding whitespace if any.
70/// It cannot parse the negative number, so some date and time cannot be formatted then
71/// parsed with the same formatting items.
72#[derive(Clone, PartialEq, Eq, Debug)]
73pub enum Numeric {
74 /// Full Gregorian year (FW=4, PW=∞).
75 /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
76 Year,
77 /// Gregorian year divided by 100 (century number; FW=PW=2). Implies the non-negative year.
78 YearDiv100,
79 /// Gregorian year modulo 100 (FW=PW=2). Cannot be negative.
80 YearMod100,
81 /// Year in the ISO week date (FW=4, PW=∞).
82 /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
83 IsoYear,
84 /// Year in the ISO week date, divided by 100 (FW=PW=2). Implies the non-negative year.
85 IsoYearDiv100,
86 /// Year in the ISO week date, modulo 100 (FW=PW=2). Cannot be negative.
87 IsoYearMod100,
88 /// Month (FW=PW=2).
89 Month,
90 /// Day of the month (FW=PW=2).
91 Day,
92 /// Week number, where the week 1 starts at the first Sunday of January (FW=PW=2).
93 WeekFromSun,
94 /// Week number, where the week 1 starts at the first Monday of January (FW=PW=2).
95 WeekFromMon,
96 /// Week number in the ISO week date (FW=PW=2).
97 IsoWeek,
98 /// Day of the week, where Sunday = 0 and Saturday = 6 (FW=PW=1).
99 NumDaysFromSun,
100 /// Day of the week, where Monday = 1 and Sunday = 7 (FW=PW=1).
101 WeekdayFromMon,
102 /// Day of the year (FW=PW=3).
103 Ordinal,
104 /// Hour number in the 24-hour clocks (FW=PW=2).
105 Hour,
106 /// Hour number in the 12-hour clocks (FW=PW=2).
107 Hour12,
108 /// The number of minutes since the last whole hour (FW=PW=2).
109 Minute,
110 /// The number of seconds since the last whole minute (FW=PW=2).
111 Second,
112 /// The number of nanoseconds since the last whole second (FW=PW=9).
113 /// Note that this is *not* left-aligned;
114 /// see also [`Fixed::Nanosecond`](./enum.Fixed.html#variant.Nanosecond).
115 Nanosecond,
116 /// The number of non-leap seconds since the midnight UTC on January 1, 1970 (FW=1, PW=∞).
117 /// For formatting, it assumes UTC upon the absence of time zone offset.
118 Timestamp,
119
120 /// Internal uses only.
121 ///
122 /// This item exists so that one can add additional internal-only formatting
123 /// without breaking major compatibility (as enum variants cannot be selectively private).
124 Internal(InternalNumeric),
125}
126
127/// An opaque type representing numeric item types for internal uses only.
128pub struct InternalNumeric {
129 _dummy: Void,
130}
131
132impl Clone for InternalNumeric {
133 fn clone(&self) -> Self {
134 match self._dummy {}
135 }
136}
137
138impl PartialEq for InternalNumeric {
139 fn eq(&self, _other: &InternalNumeric) -> bool {
140 match self._dummy {}
141 }
142}
143
144impl Eq for InternalNumeric {
145}
146
147impl fmt::Debug for InternalNumeric {
148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
149 write!(f, "<InternalNumeric>")
150 }
151}
152
153/// Fixed-format item types.
154///
155/// They have their own rules of formatting and parsing.
156/// Otherwise noted, they print in the specified cases but parse case-insensitively.
157#[derive(Clone, PartialEq, Eq, Debug)]
158pub enum Fixed {
159 /// Abbreviated month names.
160 ///
161 /// Prints a three-letter-long name in the title case, reads the same name in any case.
162 ShortMonthName,
163 /// Full month names.
164 ///
165 /// Prints a full name in the title case, reads either a short or full name in any case.
166 LongMonthName,
167 /// Abbreviated day of the week names.
168 ///
169 /// Prints a three-letter-long name in the title case, reads the same name in any case.
170 ShortWeekdayName,
171 /// Full day of the week names.
172 ///
173 /// Prints a full name in the title case, reads either a short or full name in any case.
174 LongWeekdayName,
175 /// AM/PM.
176 ///
177 /// Prints in lower case, reads in any case.
178 LowerAmPm,
179 /// AM/PM.
180 ///
181 /// Prints in upper case, reads in any case.
182 UpperAmPm,
183 /// An optional dot plus one or more digits for left-aligned nanoseconds.
184 /// May print nothing, 3, 6 or 9 digits according to the available accuracy.
185 /// See also [`Numeric::Nanosecond`](./enum.Numeric.html#variant.Nanosecond).
186 Nanosecond,
187 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3.
188 Nanosecond3,
189 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6.
190 Nanosecond6,
191 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9.
192 Nanosecond9,
193 /// Timezone name.
194 ///
195 /// It does not support parsing, its use in the parser is an immediate failure.
196 TimezoneName,
197 /// Offset from the local time to UTC (`+09:00` or `-04:00` or `+00:00`).
198 ///
199 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
200 /// The offset is limited from `-24:00` to `+24:00`,
201 /// which is same to [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
202 TimezoneOffsetColon,
203 /// Offset from the local time to UTC (`+09:00` or `-04:00` or `Z`).
204 ///
205 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace,
206 /// and `Z` can be either in upper case or in lower case.
207 /// The offset is limited from `-24:00` to `+24:00`,
208 /// which is same to [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
209 TimezoneOffsetColonZ,
210 /// Same to [`TimezoneOffsetColon`](#variant.TimezoneOffsetColon) but prints no colon.
211 /// Parsing allows an optional colon.
212 TimezoneOffset,
213 /// Same to [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ) but prints no colon.
214 /// Parsing allows an optional colon.
215 TimezoneOffsetZ,
216 /// RFC 2822 date and time syntax. Commonly used for email and MIME date and time.
217 RFC2822,
218 /// RFC 3339 & ISO 8601 date and time syntax.
219 RFC3339,
220
221 /// Internal uses only.
222 ///
223 /// This item exists so that one can add additional internal-only formatting
224 /// without breaking major compatibility (as enum variants cannot be selectively private).
225 Internal(InternalFixed),
226}
227
228/// An opaque type representing fixed-format item types for internal uses only.
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub struct InternalFixed {
231 val: InternalInternal,
232}
233
234#[derive(Debug, Clone, PartialEq, Eq)]
235enum InternalInternal {
236 /// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ), but
237 /// allows missing minutes (per [ISO 8601][iso8601]).
238 ///
239 /// # Panics
240 ///
241 /// If you try to use this for printing.
242 ///
243 /// [iso8601]: https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC
244 TimezoneOffsetPermissive,
245 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3 and there is no leading dot.
246 Nanosecond3NoDot,
247 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6 and there is no leading dot.
248 Nanosecond6NoDot,
249 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9 and there is no leading dot.
250 Nanosecond9NoDot,
251}
252
253/// A single formatting item. This is used for both formatting and parsing.
254#[derive(Clone, PartialEq, Eq, Debug)]
255pub enum Item<'a> {
256 /// A literally printed and parsed text.
257 Literal(&'a str),
258 /// Same to `Literal` but with the string owned by the item.
259 #[cfg(any(feature = "alloc", feature = "std", test))]
260 OwnedLiteral(Box<str>),
261 /// Whitespace. Prints literally but reads zero or more whitespace.
262 Space(&'a str),
263 /// Same to `Space` but with the string owned by the item.
264 #[cfg(any(feature = "alloc", feature = "std", test))]
265 OwnedSpace(Box<str>),
266 /// Numeric item. Can be optionally padded to the maximal length (if any) when formatting;
267 /// the parser simply ignores any padded whitespace and zeroes.
268 Numeric(Numeric, Pad),
269 /// Fixed-format item.
270 Fixed(Fixed),
271 /// Issues a formatting error. Used to signal an invalid format string.
272 Error,
273}
274
275macro_rules! lit { ($x:expr) => (Item::Literal($x)) }
276macro_rules! sp { ($x:expr) => (Item::Space($x)) }
277macro_rules! num { ($x:ident) => (Item::Numeric(Numeric::$x, Pad::None)) }
278macro_rules! num0 { ($x:ident) => (Item::Numeric(Numeric::$x, Pad::Zero)) }
279macro_rules! nums { ($x:ident) => (Item::Numeric(Numeric::$x, Pad::Space)) }
280macro_rules! fix { ($x:ident) => (Item::Fixed(Fixed::$x)) }
281macro_rules! internal_fix { ($x:ident) => (Item::Fixed(Fixed::Internal(InternalFixed { val: InternalInternal::$x })))}
282
283/// An error from the `parse` function.
284#[derive(Debug, Clone, PartialEq, Eq, Copy)]
285pub struct ParseError(ParseErrorKind);
286
287#[derive(Debug, Clone, PartialEq, Eq, Copy)]
288enum ParseErrorKind {
289 /// Given field is out of permitted range.
290 OutOfRange,
291
292 /// There is no possible date and time value with given set of fields.
293 ///
294 /// This does not include the out-of-range conditions, which are trivially invalid.
295 /// It includes the case that there are one or more fields that are inconsistent to each other.
296 Impossible,
297
298 /// Given set of fields is not enough to make a requested date and time value.
299 ///
300 /// Note that there *may* be a case that given fields constrain the possible values so much
301 /// that there is a unique possible value. Chrono only tries to be correct for
302 /// most useful sets of fields however, as such constraint solving can be expensive.
303 NotEnough,
304
305 /// The input string has some invalid character sequence for given formatting items.
306 Invalid,
307
308 /// The input string has been prematurely ended.
309 TooShort,
310
311 /// All formatting items have been read but there is a remaining input.
312 TooLong,
313
314 /// There was an error on the formatting string, or there were non-supported formating items.
315 BadFormat,
316}
317
318/// Same to `Result<T, ParseError>`.
319pub type ParseResult<T> = Result<T, ParseError>;
320
321impl fmt::Display for ParseError {
322 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
323 match self.0 {
324 ParseErrorKind::OutOfRange => write!(f, "input is out of range"),
325 ParseErrorKind::Impossible => write!(f, "no possible date and time matching input"),
326 ParseErrorKind::NotEnough => write!(f, "input is not enough for unique date and time"),
327 ParseErrorKind::Invalid => write!(f, "input contains invalid characters"),
328 ParseErrorKind::TooShort => write!(f, "premature end of input"),
329 ParseErrorKind::TooLong => write!(f, "trailing input"),
330 ParseErrorKind::BadFormat => write!(f, "bad or unsupported format string"),
331 }
332 }
333}
334
335#[cfg(any(feature = "std", test))]
336impl Error for ParseError {
337 #[allow(deprecated)]
338 fn description(&self) -> &str {
339 "parser error, see to_string() for details"
340 }
341}
342
343// to be used in this module and submodules
344const OUT_OF_RANGE: ParseError = ParseError(ParseErrorKind::OutOfRange);
345const IMPOSSIBLE: ParseError = ParseError(ParseErrorKind::Impossible);
346const NOT_ENOUGH: ParseError = ParseError(ParseErrorKind::NotEnough);
347const INVALID: ParseError = ParseError(ParseErrorKind::Invalid);
348const TOO_SHORT: ParseError = ParseError(ParseErrorKind::TooShort);
349const TOO_LONG: ParseError = ParseError(ParseErrorKind::TooLong);
350const BAD_FORMAT: ParseError = ParseError(ParseErrorKind::BadFormat);
351
352/// Tries to format given arguments with given formatting items.
353/// Internally used by `DelayedFormat`.
354#[cfg(any(feature = "alloc", feature = "std", test))]
355pub fn format<'a, I, B>(
356 w: &mut fmt::Formatter,
357 date: Option<&NaiveDate>,
358 time: Option<&NaiveTime>,
359 off: Option<&(String, FixedOffset)>,
360 items: I,
361) -> fmt::Result
362 where I: Iterator<Item=B> + Clone, B: Borrow<Item<'a>>
363{
364 // full and abbreviated month and weekday names
365 static SHORT_MONTHS: [&'static str; 12] =
366 ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
367 static LONG_MONTHS: [&'static str; 12] =
368 ["January", "February", "March", "April", "May", "June",
369 "July", "August", "September", "October", "November", "December"];
370 static SHORT_WEEKDAYS: [&'static str; 7] =
371 ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
372 static LONG_WEEKDAYS: [&'static str; 7] =
373 ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
374
375 use core::fmt::Write;
376 let mut result = String::new();
377
378 for item in items {
379 match item.borrow() {
380 &Item::Literal(s) | &Item::Space(s) => result.push_str(s),
381 #[cfg(any(feature = "alloc", feature = "std", test))]
382 &Item::OwnedLiteral(ref s) | &Item::OwnedSpace(ref s) => result.push_str(s),
383
384 &Item::Numeric(ref spec, ref pad) => {
385 use self::Numeric::*;
386
387 let week_from_sun = |d: &NaiveDate|
388 (d.ordinal() as i32 - d.weekday().num_days_from_sunday() as i32 + 7) / 7;
389 let week_from_mon = |d: &NaiveDate|
390 (d.ordinal() as i32 - d.weekday().num_days_from_monday() as i32 + 7) / 7;
391
392 let (width, v) = match spec {
393 &Year => (4, date.map(|d| i64::from(d.year()))),
394 &YearDiv100 => (2, date.map(|d| div_floor(i64::from(d.year()), 100))),
395 &YearMod100 => (2, date.map(|d| mod_floor(i64::from(d.year()), 100))),
396 &IsoYear => (4, date.map(|d| i64::from(d.iso_week().year()))),
397 &IsoYearDiv100 => (2, date.map(|d| div_floor(
398 i64::from(d.iso_week().year()), 100))),
399 &IsoYearMod100 => (2, date.map(|d| mod_floor(
400 i64::from(d.iso_week().year()), 100))),
401 &Month => (2, date.map(|d| i64::from(d.month()))),
402 &Day => (2, date.map(|d| i64::from(d.day()))),
403 &WeekFromSun => (2, date.map(|d| i64::from(week_from_sun(d)))),
404 &WeekFromMon => (2, date.map(|d| i64::from(week_from_mon(d)))),
405 &IsoWeek => (2, date.map(|d| i64::from(d.iso_week().week()))),
406 &NumDaysFromSun => (1, date.map(|d| i64::from(d.weekday()
407 .num_days_from_sunday()))),
408 &WeekdayFromMon => (1, date.map(|d| i64::from(d.weekday()
409 .number_from_monday()))),
410 &Ordinal => (3, date.map(|d| i64::from(d.ordinal()))),
411 &Hour => (2, time.map(|t| i64::from(t.hour()))),
412 &Hour12 => (2, time.map(|t| i64::from(t.hour12().1))),
413 &Minute => (2, time.map(|t| i64::from(t.minute()))),
414 &Second => (2, time.map(|t| i64::from(t.second() +
415 t.nanosecond() / 1_000_000_000))),
416 &Nanosecond => (9, time.map(|t| i64::from(t.nanosecond() % 1_000_000_000))),
417 &Timestamp => (1, match (date, time, off) {
418 (Some(d), Some(t), None) =>
419 Some(d.and_time(*t).timestamp()),
420 (Some(d), Some(t), Some(&(_, off))) =>
421 Some((d.and_time(*t) - off).timestamp()),
422 (_, _, _) => None
423 }),
424
425 // for the future expansion
426 &Internal(ref int) => match int._dummy {},
427 };
428
429
430 if let Some(v) = v {
431 if (spec == &Year || spec == &IsoYear) && !(0 <= v && v < 10_000) {
432 // non-four-digit years require an explicit sign as per ISO 8601
433 match pad {
434 &Pad::None => write!(result, "{:+}", v),
435 &Pad::Zero => write!(result, "{:+01$}", v, width + 1),
436 &Pad::Space => write!(result, "{:+1$}", v, width + 1),
437 }
438 } else {
439 match pad {
440 &Pad::None => write!(result, "{}", v),
441 &Pad::Zero => write!(result, "{:01$}", v, width),
442 &Pad::Space => write!(result, "{:1$}", v, width),
443 }
444 }?
445 } else {
446 return Err(fmt::Error) // insufficient arguments for given format
447 }
448 },
449
450 &Item::Fixed(ref spec) => {
451 use self::Fixed::*;
452
453 /// Prints an offset from UTC in the format of `+HHMM` or `+HH:MM`.
454 /// `Z` instead of `+00[:]00` is allowed when `allow_zulu` is true.
455 fn write_local_minus_utc(
456 result: &mut String,
457 off: FixedOffset,
458 allow_zulu: bool,
459 use_colon: bool,
460 ) -> fmt::Result {
461 let off = off.local_minus_utc();
462 if !allow_zulu || off != 0 {
463 let (sign, off) = if off < 0 {('-', -off)} else {('+', off)};
464 if use_colon {
465 write!(result, "{}{:02}:{:02}", sign, off / 3600, off / 60 % 60)
466 } else {
467 write!(result, "{}{:02}{:02}", sign, off / 3600, off / 60 % 60)
468 }
469 } else {
470 result.push_str("Z");
471 Ok(())
472 }
473 }
474
475 let ret = match spec {
476 &ShortMonthName =>
477 date.map(|d| {
478 result.push_str(SHORT_MONTHS[d.month0() as usize]);
479 Ok(())
480 }),
481 &LongMonthName =>
482 date.map(|d| {
483 result.push_str(LONG_MONTHS[d.month0() as usize]);
484 Ok(())
485 }),
486 &ShortWeekdayName =>
487 date.map(|d| {
488 result.push_str(
489 SHORT_WEEKDAYS[d.weekday().num_days_from_monday() as usize]
490 );
491 Ok(())
492 }),
493 &LongWeekdayName =>
494 date.map(|d| {
495 result.push_str(
496 LONG_WEEKDAYS[d.weekday().num_days_from_monday() as usize]
497 );
498 Ok(())
499 }),
500 &LowerAmPm =>
501 time.map(|t| {
502 result.push_str(if t.hour12().0 {"pm"} else {"am"});
503 Ok(())
504 }),
505 &UpperAmPm =>
506 time.map(|t| {
507 result.push_str(if t.hour12().0 {"PM"} else {"AM"});
508 Ok(())
509 }),
510 &Nanosecond =>
511 time.map(|t| {
512 let nano = t.nanosecond() % 1_000_000_000;
513 if nano == 0 {
514 Ok(())
515 } else if nano % 1_000_000 == 0 {
516 write!(result, ".{:03}", nano / 1_000_000)
517 } else if nano % 1_000 == 0 {
518 write!(result, ".{:06}", nano / 1_000)
519 } else {
520 write!(result, ".{:09}", nano)
521 }
522 }),
523 &Nanosecond3 =>
524 time.map(|t| {
525 let nano = t.nanosecond() % 1_000_000_000;
526 write!(result, ".{:03}", nano / 1_000_000)
527 }),
528 &Nanosecond6 =>
529 time.map(|t| {
530 let nano = t.nanosecond() % 1_000_000_000;
531 write!(result, ".{:06}", nano / 1_000)
532 }),
533 &Nanosecond9 =>
534 time.map(|t| {
535 let nano = t.nanosecond() % 1_000_000_000;
536 write!(result, ".{:09}", nano)
537 }),
538 &Internal(InternalFixed { val: InternalInternal::Nanosecond3NoDot }) =>
539 time.map(|t| {
540 let nano = t.nanosecond() % 1_000_000_000;
541 write!(result, "{:03}", nano / 1_000_000)
542 }),
543 &Internal(InternalFixed { val: InternalInternal::Nanosecond6NoDot }) =>
544 time.map(|t| {
545 let nano = t.nanosecond() % 1_000_000_000;
546 write!(result, "{:06}", nano / 1_000)
547 }),
548 &Internal(InternalFixed { val: InternalInternal::Nanosecond9NoDot }) =>
549 time.map(|t| {
550 let nano = t.nanosecond() % 1_000_000_000;
551 write!(result, "{:09}", nano)
552 }),
553 &TimezoneName =>
554 off.map(|&(ref name, _)| {
555 result.push_str(name);
556 Ok(())
557 }),
558 &TimezoneOffsetColon =>
559 off.map(|&(_, off)| write_local_minus_utc(&mut result, off, false, true)),
560 &TimezoneOffsetColonZ =>
561 off.map(|&(_, off)| write_local_minus_utc(&mut result, off, true, true)),
562 &TimezoneOffset =>
563 off.map(|&(_, off)| write_local_minus_utc(&mut result, off, false, false)),
564 &TimezoneOffsetZ =>
565 off.map(|&(_, off)| write_local_minus_utc(&mut result, off, true, false)),
566 &Internal(InternalFixed { val: InternalInternal::TimezoneOffsetPermissive }) =>
567 panic!("Do not try to write %#z it is undefined"),
568 &RFC2822 => // same to `%a, %e %b %Y %H:%M:%S %z`
569 if let (Some(d), Some(t), Some(&(_, off))) = (date, time, off) {
570 let sec = t.second() + t.nanosecond() / 1_000_000_000;
571 write!(
572 result,
573 "{}, {:02} {} {:04} {:02}:{:02}:{:02} ",
574 SHORT_WEEKDAYS[d.weekday().num_days_from_monday() as usize],
575 d.day(), SHORT_MONTHS[d.month0() as usize], d.year(),
576 t.hour(), t.minute(), sec
577 )?;
578 Some(write_local_minus_utc(&mut result, off, false, false))
579 } else {
580 None
581 },
582 &RFC3339 => // same to `%Y-%m-%dT%H:%M:%S%.f%:z`
583 if let (Some(d), Some(t), Some(&(_, off))) = (date, time, off) {
584 // reuse `Debug` impls which already print ISO 8601 format.
585 // this is faster in this way.
586 write!(result, "{:?}T{:?}", d, t)?;
587 Some(write_local_minus_utc(&mut result, off, false, true))
588 } else {
589 None
590 },
591 };
592
593 match ret {
594 Some(ret) => ret?,
595 None => return Err(fmt::Error), // insufficient arguments for given format
596 }
597 },
598
599 &Item::Error => return Err(fmt::Error),
600 }
601 }
602
603 w.pad(&result)
604}
605
606mod parsed;
607
608// due to the size of parsing routines, they are in separate modules.
609mod scan;
610mod parse;
611
612pub mod strftime;
613
614/// A *temporary* object which can be used as an argument to `format!` or others.
615/// This is normally constructed via `format` methods of each date and time type.
616#[cfg(any(feature = "alloc", feature = "std", test))]
617#[derive(Debug)]
618pub struct DelayedFormat<I> {
619 /// The date view, if any.
620 date: Option<NaiveDate>,
621 /// The time view, if any.
622 time: Option<NaiveTime>,
623 /// The name and local-to-UTC difference for the offset (timezone), if any.
624 off: Option<(String, FixedOffset)>,
625 /// An iterator returning formatting items.
626 items: I,
627}
628
629#[cfg(any(feature = "alloc", feature = "std", test))]
630impl<'a, I: Iterator<Item=B> + Clone, B: Borrow<Item<'a>>> DelayedFormat<I> {
631 /// Makes a new `DelayedFormat` value out of local date and time.
632 pub fn new(date: Option<NaiveDate>, time: Option<NaiveTime>, items: I) -> DelayedFormat<I> {
633 DelayedFormat { date: date, time: time, off: None, items: items }
634 }
635
636 /// Makes a new `DelayedFormat` value out of local date and time and UTC offset.
637 pub fn new_with_offset<Off>(date: Option<NaiveDate>, time: Option<NaiveTime>,
638 offset: &Off, items: I) -> DelayedFormat<I>
639 where Off: Offset + fmt::Display {
640 let name_and_diff = (offset.to_string(), offset.fix());
641 DelayedFormat { date: date, time: time, off: Some(name_and_diff), items: items }
642 }
643}
644
645#[cfg(any(feature = "alloc", feature = "std", test))]
646impl<'a, I: Iterator<Item=B> + Clone, B: Borrow<Item<'a>>> fmt::Display for DelayedFormat<I> {
647 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
648 format(f, self.date.as_ref(), self.time.as_ref(), self.off.as_ref(), self.items.clone())
649 }
650}
651
652// this implementation is here only because we need some private code from `scan`
653
654/// Parsing a `str` into a `Weekday` uses the format [`%W`](./format/strftime/index.html).
655///
656/// # Example
657///
658/// ~~~~
659/// use chrono::Weekday;
660///
661/// assert_eq!("Sunday".parse::<Weekday>(), Ok(Weekday::Sun));
662/// assert!("any day".parse::<Weekday>().is_err());
663/// ~~~~
664///
665/// The parsing is case-insensitive.
666///
667/// ~~~~
668/// # use chrono::Weekday;
669/// assert_eq!("mON".parse::<Weekday>(), Ok(Weekday::Mon));
670/// ~~~~
671///
672/// Only the shortest form (e.g. `sun`) and the longest form (e.g. `sunday`) is accepted.
673///
674/// ~~~~
675/// # use chrono::Weekday;
676/// assert!("thurs".parse::<Weekday>().is_err());
677/// ~~~~
678impl FromStr for Weekday {
679 type Err = ParseWeekdayError;
680
681 fn from_str(s: &str) -> Result<Self, Self::Err> {
682 if let Ok(("", w)) = scan::short_or_long_weekday(s) {
683 Ok(w)
684 } else {
685 Err(ParseWeekdayError { _dummy: () })
686 }
687 }
688}