]> git.proxmox.com Git - rustc.git/blob - src/vendor/chrono/src/format/mod.rs
New upstream version 1.27.1+dfsg1
[rustc.git] / src / vendor / chrono / src / 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 use std::fmt;
19 use std::str::FromStr;
20 use std::error::Error;
21
22 use {Datelike, Timelike, Weekday, ParseWeekdayError};
23 use div::{div_floor, mod_floor};
24 use offset::{Offset, FixedOffset};
25 use naive::{NaiveDate, NaiveTime};
26
27 pub use self::strftime::StrftimeItems;
28 pub use self::parsed::Parsed;
29 pub use self::parse::parse;
30
31 /// An unhabitated type used for `InternalNumeric` and `InternalFixed` below.
32 #[derive(Clone, PartialEq, Eq)]
33 enum Void {}
34
35 /// Padding characters for numeric items.
36 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
37 pub enum Pad {
38 /// No padding.
39 None,
40 /// Zero (`0`) padding.
41 Zero,
42 /// Space padding.
43 Space,
44 }
45
46 /// Numeric item types.
47 /// They have associated formatting width (FW) and parsing width (PW).
48 ///
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.
53 ///
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)]
60 pub enum Numeric {
61 /// Full Gregorian year (FW=4, PW=∞).
62 /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
63 Year,
64 /// Gregorian year divided by 100 (century number; FW=PW=2). Implies the non-negative year.
65 YearDiv100,
66 /// Gregorian year modulo 100 (FW=PW=2). Cannot be negative.
67 YearMod100,
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.
70 IsoYear,
71 /// Year in the ISO week date, divided by 100 (FW=PW=2). Implies the non-negative year.
72 IsoYearDiv100,
73 /// Year in the ISO week date, modulo 100 (FW=PW=2). Cannot be negative.
74 IsoYearMod100,
75 /// Month (FW=PW=2).
76 Month,
77 /// Day of the month (FW=PW=2).
78 Day,
79 /// Week number, where the week 1 starts at the first Sunday of January (FW=PW=2).
80 WeekFromSun,
81 /// Week number, where the week 1 starts at the first Monday of January (FW=PW=2).
82 WeekFromMon,
83 /// Week number in the ISO week date (FW=PW=2).
84 IsoWeek,
85 /// Day of the week, where Sunday = 0 and Saturday = 6 (FW=PW=1).
86 NumDaysFromSun,
87 /// Day of the week, where Monday = 1 and Sunday = 7 (FW=PW=1).
88 WeekdayFromMon,
89 /// Day of the year (FW=PW=3).
90 Ordinal,
91 /// Hour number in the 24-hour clocks (FW=PW=2).
92 Hour,
93 /// Hour number in the 12-hour clocks (FW=PW=2).
94 Hour12,
95 /// The number of minutes since the last whole hour (FW=PW=2).
96 Minute,
97 /// The number of seconds since the last whole minute (FW=PW=2).
98 Second,
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).
102 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.
105 Timestamp,
106
107 /// Internal uses only.
108 ///
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),
112 }
113
114 /// An opaque type representing numeric item types for internal uses only.
115 pub struct InternalNumeric {
116 _dummy: Void,
117 }
118
119 impl Clone for InternalNumeric {
120 fn clone(&self) -> Self {
121 match self._dummy {}
122 }
123 }
124
125 impl PartialEq for InternalNumeric {
126 fn eq(&self, _other: &InternalNumeric) -> bool {
127 match self._dummy {}
128 }
129 }
130
131 impl Eq for InternalNumeric {
132 }
133
134 impl fmt::Debug for InternalNumeric {
135 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
136 write!(f, "<InternalNumeric>")
137 }
138 }
139
140 /// Fixed-format item types.
141 ///
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)]
145 pub enum Fixed {
146 /// Abbreviated month names.
147 ///
148 /// Prints a three-letter-long name in the title case, reads the same name in any case.
149 ShortMonthName,
150 /// Full month names.
151 ///
152 /// Prints a full name in the title case, reads either a short or full name in any case.
153 LongMonthName,
154 /// Abbreviated day of the week names.
155 ///
156 /// Prints a three-letter-long name in the title case, reads the same name in any case.
157 ShortWeekdayName,
158 /// Full day of the week names.
159 ///
160 /// Prints a full name in the title case, reads either a short or full name in any case.
161 LongWeekdayName,
162 /// AM/PM.
163 ///
164 /// Prints in lower case, reads in any case.
165 LowerAmPm,
166 /// AM/PM.
167 ///
168 /// Prints in upper case, reads in any case.
169 UpperAmPm,
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).
173 Nanosecond,
174 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3.
175 Nanosecond3,
176 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6.
177 Nanosecond6,
178 /// Same to [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9.
179 Nanosecond9,
180 /// Timezone name.
181 ///
182 /// It does not support parsing, its use in the parser is an immediate failure.
183 TimezoneName,
184 /// Offset from the local time to UTC (`+09:00` or `-04:00` or `+00:00`).
185 ///
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.
189 TimezoneOffsetColon,
190 /// Offset from the local time to UTC (`+09:00` or `-04:00` or `Z`).
191 ///
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.
199 TimezoneOffset,
200 /// Same to [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ) but prints no colon.
201 /// Parsing allows an optional colon.
202 TimezoneOffsetZ,
203 /// RFC 2822 date and time syntax. Commonly used for email and MIME date and time.
204 RFC2822,
205 /// RFC 3339 & ISO 8601 date and time syntax.
206 RFC3339,
207
208 /// Internal uses only.
209 ///
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),
213 }
214
215 /// An opaque type representing fixed-format item types for internal uses only.
216 pub struct InternalFixed {
217 _dummy: Void,
218 }
219
220 impl Clone for InternalFixed {
221 fn clone(&self) -> Self {
222 match self._dummy {}
223 }
224 }
225
226 impl PartialEq for InternalFixed {
227 fn eq(&self, _other: &InternalFixed) -> bool {
228 match self._dummy {}
229 }
230 }
231
232 impl Eq for InternalFixed {
233 }
234
235 impl fmt::Debug for InternalFixed {
236 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
237 write!(f, "<InternalFixed>")
238 }
239 }
240
241 /// A single formatting item. This is used for both formatting and parsing.
242 #[derive(Clone, PartialEq, Eq, Debug)]
243 pub enum Item<'a> {
244 /// A literally printed and parsed text.
245 Literal(&'a str),
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.
249 Space(&'a str),
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.
256 Fixed(Fixed),
257 /// Issues a formatting error. Used to signal an invalid format string.
258 Error,
259 }
260
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)) }
267
268 /// An error from the `parse` function.
269 #[derive(Debug, Clone, PartialEq, Eq, Copy)]
270 pub struct ParseError(ParseErrorKind);
271
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.
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 {
309 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
310 self.description().fmt(f)
311 }
312 }
313
314 impl Error for ParseError {
315 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`.
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"];
352
353 for item in items {
354 match item {
355 Item::Literal(s) | Item::Space(s) => try!(write!(w, "{}", s)),
356 Item::OwnedLiteral(ref s) | Item::OwnedSpace(ref s) => try!(write!(w, "{}", s)),
357
358 Item::Numeric(spec, pad) => {
359 use self::Numeric::*;
360
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;
365
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()),
396 (_, _, _) => None
397 }),
398
399 // for the future expansion
400 Internal(ref int) => match int._dummy {},
401 };
402
403 if let Some(v) = v {
404 if (spec == Year || spec == IsoYear) && !(0 <= v && v < 10_000) {
405 // non-four-digit years require an explicit sign as per ISO 8601
406 match pad {
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)),
410 }
411 } else {
412 match pad {
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)),
416 }
417 }
418 } else {
419 return Err(fmt::Error); // insufficient arguments for given format
420 }
421 },
422
423 Item::Fixed(spec) => {
424 use self::Fixed::*;
425
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)};
433 if use_colon {
434 write!(w, "{}{:02}:{:02}", sign, off / 3600, off / 60 % 60)
435 } else {
436 write!(w, "{}{:02}{:02}", sign, off / 3600, off / 60 % 60)
437 }
438 } else {
439 write!(w, "Z")
440 }
441 }
442
443 let ret = match spec {
444 ShortMonthName =>
445 date.map(|d| write!(w, "{}", SHORT_MONTHS[d.month0() as usize])),
446 LongMonthName =>
447 date.map(|d| write!(w, "{}", LONG_MONTHS[d.month0() as usize])),
448 ShortWeekdayName =>
449 date.map(|d| write!(w, "{}",
450 SHORT_WEEKDAYS[d.weekday().num_days_from_monday() as usize])),
451 LongWeekdayName =>
452 date.map(|d| write!(w, "{}",
453 LONG_WEEKDAYS[d.weekday().num_days_from_monday() as usize])),
454 LowerAmPm =>
455 time.map(|t| write!(w, "{}", if t.hour12().0 {"pm"} else {"am"})),
456 UpperAmPm =>
457 time.map(|t| write!(w, "{}", if t.hour12().0 {"PM"} else {"AM"})),
458 Nanosecond =>
459 time.map(|t| {
460 let nano = t.nanosecond() % 1_000_000_000;
461 if nano == 0 {
462 Ok(())
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)
467 } else {
468 write!(w, ".{:09}", nano)
469 }
470 }),
471 Nanosecond3 =>
472 time.map(|t| {
473 let nano = t.nanosecond() % 1_000_000_000;
474 write!(w, ".{:03}", nano / 1_000_000)
475 }),
476 Nanosecond6 =>
477 time.map(|t| {
478 let nano = t.nanosecond() % 1_000_000_000;
479 write!(w, ".{:06}", nano / 1_000)
480 }),
481 Nanosecond9 =>
482 time.map(|t| {
483 let nano = t.nanosecond() % 1_000_000_000;
484 write!(w, ".{:09}", nano)
485 }),
486 TimezoneName =>
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)),
492 TimezoneOffset =>
493 off.map(|&(_, off)| write_local_minus_utc(w, off, false, false)),
494 TimezoneOffsetZ =>
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))
504 } else {
505 None
506 },
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))
513 } else {
514 None
515 },
516
517 // for the future expansion
518 Internal(ref int) => match int._dummy {},
519 };
520
521 match ret {
522 Some(ret) => try!(ret),
523 None => return Err(fmt::Error), // insufficient arguments for given format
524 }
525 },
526
527 Item::Error => return Err(fmt::Error),
528 }
529 }
530
531 Ok(())
532 }
533
534 mod parsed;
535
536 // due to the size of parsing routines, they are in separate modules.
537 mod scan;
538 mod parse;
539
540 pub mod strftime;
541
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.
544 #[derive(Debug)]
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.
553 items: I,
554 }
555
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 }
560 }
561
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 }
568 }
569 }
570
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())
574 }
575 }
576
577 // this implementation is here only because we need some private code from `scan`
578
579 /// Parsing a `str` into a `Weekday` uses the format [`%W`](./format/strftime/index.html).
580 ///
581 /// # Example
582 ///
583 /// ~~~~
584 /// use chrono::Weekday;
585 ///
586 /// assert_eq!("Sunday".parse::<Weekday>(), Ok(Weekday::Sun));
587 /// assert!("any day".parse::<Weekday>().is_err());
588 /// ~~~~
589 ///
590 /// The parsing is case-insensitive.
591 ///
592 /// ~~~~
593 /// # use chrono::Weekday;
594 /// assert_eq!("mON".parse::<Weekday>(), Ok(Weekday::Mon));
595 /// ~~~~
596 ///
597 /// Only the shortest form (e.g. `sun`) and the longest form (e.g. `sunday`) is accepted.
598 ///
599 /// ~~~~
600 /// # use chrono::Weekday;
601 /// assert!("thurs".parse::<Weekday>().is_err());
602 /// ~~~~
603 impl FromStr for Weekday {
604 type Err = ParseWeekdayError;
605
606 fn from_str(s: &str) -> Result<Self, Self::Err> {
607 if let Ok(("", w)) = scan::short_or_long_weekday(s) {
608 Ok(w)
609 } else {
610 Err(ParseWeekdayError { _dummy: () })
611 }
612 }
613 }
614