Struct StrftimeItems

pub struct StrftimeItems<'a> { /* private fields */ }

Parsing iterator for strftime-like format strings.

See the format::strftime module for supported formatting specifiers.

StrftimeItems is used in combination with more low-level methods such as format::parse() or format_with_items.

If formatting or parsing date and time values is not performance-critical, the methods parse_from_str and format on types such as DateTime are easier to use.

Implementations

impl<'a> StrftimeItems<'a>

const fn new(s: &'a str) -> StrftimeItems<'a>

Creates a new parsing iterator from a strftime-like format string.

Errors

While iterating Item::Error will be returned if the format string contains an invalid or unrecognized formatting specifier.

Example

use chrono::format::*;

let strftime_parser = StrftimeItems::new("%F"); // %F: year-month-day (ISO 8601)

const ISO8601_YMD_ITEMS: &[Item<'static>] = &[
    Item::Numeric(Numeric::Year, Pad::Zero),
    Item::Literal("-"),
    Item::Numeric(Numeric::Month, Pad::Zero),
    Item::Literal("-"),
    Item::Numeric(Numeric::Day, Pad::Zero),
];
assert!(strftime_parser.eq(ISO8601_YMD_ITEMS.iter().cloned()));
const fn new_lenient(s: &'a str) -> StrftimeItems<'a>

The same as StrftimeItems::new, but returns Item::Literal instead of Item::Error.

Useful for formatting according to potentially invalid format strings.

Example

use chrono::format::*;

let strftime_parser = StrftimeItems::new_lenient("%Y-%Q"); // %Y: year, %Q: invalid

const ITEMS: &[Item<'static>] = &[
    Item::Numeric(Numeric::Year, Pad::Zero),
    Item::Literal("-"),
    Item::Literal("%Q"),
];
println!("{:?}", strftime_parser.clone().collect::<Vec<_>>());
assert!(strftime_parser.eq(ITEMS.iter().cloned()));
fn parse(self) -> Result<Vec<Item<'a>>, ParseError>

Parse format string into a Vec of formatting Item's.

If you need to format or parse multiple values with the same format string, it is more efficient to convert it to a Vec of formatting Item's than to re-parse the format string on every use.

The format_with_items methods on DateTime, NaiveDateTime, NaiveDate and NaiveTime accept the result for formatting. format::parse() can make use of it for parsing.

Errors

Returns an error if the format string contains an invalid or unrecognized formatting specifier and the StrftimeItems wasn't constructed with [new_lenient][Self::new_lenient].

Example

use chrono::format::{parse, Parsed, StrftimeItems};
use chrono::NaiveDate;

let fmt_items = StrftimeItems::new("%e %b %Y %k.%M").parse()?;
let datetime = NaiveDate::from_ymd_opt(2023, 7, 11).unwrap().and_hms_opt(9, 0, 0).unwrap();

// Formatting
assert_eq!(
    datetime.format_with_items(fmt_items.as_slice().iter()).to_string(),
    "11 Jul 2023  9.00"
);

// Parsing
let mut parsed = Parsed::new();
parse(&mut parsed, "11 Jul 2023  9.00", fmt_items.as_slice().iter())?;
let parsed_dt = parsed.to_naive_datetime_with_offset(0)?;
assert_eq!(parsed_dt, datetime);
# Ok::<(), chrono::ParseError>(())
fn parse_to_owned(self) -> Result<Vec<Item<'static>>, ParseError>

Parse format string into a Vec of Item's that contain no references to slices of the format string.

A Vec created with StrftimeItems::parse contains references to the format string, binding the lifetime of the Vec to that string. StrftimeItems::parse_to_owned will convert the references to owned types.

Errors

Returns an error if the format string contains an invalid or unrecognized formatting specifier and the StrftimeItems wasn't constructed with [new_lenient][Self::new_lenient].

Example

use chrono::format::{Item, ParseError, StrftimeItems};
use chrono::NaiveDate;

fn format_items(date_fmt: &str, time_fmt: &str) -> Result<Vec<Item<'static>>, ParseError> {
    // `fmt_string` is dropped at the end of this function.
    let fmt_string = format!("{} {}", date_fmt, time_fmt);
    StrftimeItems::new(&fmt_string).parse_to_owned()
}

let fmt_items = format_items("%e %b %Y", "%k.%M")?;
let datetime = NaiveDate::from_ymd_opt(2023, 7, 11).unwrap().and_hms_opt(9, 0, 0).unwrap();

assert_eq!(
    datetime.format_with_items(fmt_items.as_slice().iter()).to_string(),
    "11 Jul 2023  9.00"
);
# Ok::<(), ParseError>(())

Trait Implementations

impl<'a> Clone for StrftimeItems<'a>

fn clone(&self) -> StrftimeItems<'a>

impl<'a> Debug for StrftimeItems<'a>

fn fmt(&self, f: &mut Formatter<'_>) -> Result

impl<'a> Iterator for StrftimeItems<'a>

type Item = Item<'a>;
fn next(&mut self) -> Option<Item<'a>>

Auto Trait Implementations

impl<'a> Freeze for StrftimeItems<'a>

impl<'a> RefUnwindSafe for StrftimeItems<'a>

impl<'a> Send for StrftimeItems<'a>

impl<'a> Sync for StrftimeItems<'a>

impl<'a> Unpin for StrftimeItems<'a>

impl<'a> UnsafeUnpin for StrftimeItems<'a>

impl<'a> UnwindSafe for StrftimeItems<'a>

Blanket Implementations

impl<I> IntoIterator for StrftimeItems<'a> where I: Iterator,

type Item = <I as Iterator>::Item;
type IntoIter = I;
fn into_iter(self) -> I

impl<T> Any for StrftimeItems<'a> where T: 'static + ?Sized,

fn type_id(&self) -> TypeId

impl<T> Borrow<T> for StrftimeItems<'a> where T: ?Sized,

fn borrow(&self) -> &T

impl<T> BorrowMut<T> for StrftimeItems<'a> where T: ?Sized,

fn borrow_mut(&mut self) -> &mut T

impl<T> CloneToUninit for StrftimeItems<'a> where T: Clone,

unsafe fn clone_to_uninit(&self, dest: *mut u8)

impl<T> From<T> for StrftimeItems<'a>

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> ToOwned for StrftimeItems<'a> where T: Clone,

type Owned = T;
fn to_owned(&self) -> T
fn clone_into(&self, target: &mut T)

impl<T, U> Into<U> for StrftimeItems<'a> where U: From<T>,

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

impl<T, U> TryFrom<U> for StrftimeItems<'a> where U: Into<T>,

type Error = Infallible;
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

impl<T, U> TryInto<U> for StrftimeItems<'a> where U: TryFrom<T>,

type Error = <U as TryFrom<T>>::Error;
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>