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