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