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