chrono::format

Struct Parsed

Source
pub struct Parsed { /* private fields */ }
Expand description

A type to hold parsed fields of date and time that can check all fields are consistent.

There are three classes of methods:

  • set_* methods to set fields you have available. They do a basic range check, and if the same field is set more than once it is checked for consistency.

  • to_* methods try to make a concrete date and time value out of set fields. They fully check that all fields are consistent and whether the date/datetime exists.

  • Methods to inspect the parsed fields.

Parsed is used internally by all parsing functions in chrono. It is a public type so that it can be used to write custom parsers that reuse the resolving algorithm, or to inspect the results of a string parsed with chrono without converting it to concrete types.

§Resolving algorithm

Resolving date/time parts is littered with lots of corner cases, which is why common date/time parsers do not implement it correctly.

Chrono provides a complete resolution algorithm that checks all fields for consistency via the Parsed type.

As an easy example, consider RFC 2822. The RFC 2822 date and time format has a day of the week part, which should be consistent with the other date parts. But a strptime-based parse would happily accept inconsistent input:

>>> import time
>>> time.strptime('Wed, 31 Dec 2014 04:26:40 +0000',
                  '%a, %d %b %Y %H:%M:%S +0000')
time.struct_time(tm_year=2014, tm_mon=12, tm_mday=31,
                 tm_hour=4, tm_min=26, tm_sec=40,
                 tm_wday=2, tm_yday=365, tm_isdst=-1)
>>> time.strptime('Thu, 31 Dec 2014 04:26:40 +0000',
                  '%a, %d %b %Y %H:%M:%S +0000')
time.struct_time(tm_year=2014, tm_mon=12, tm_mday=31,
                 tm_hour=4, tm_min=26, tm_sec=40,
                 tm_wday=3, tm_yday=365, tm_isdst=-1)

§Example

Let’s see how Parsed correctly detects the second RFC 2822 string from before is inconsistent.

use chrono::format::{ParseErrorKind, Parsed};
use chrono::Weekday;

let mut parsed = Parsed::new();
parsed.set_weekday(Weekday::Wed)?;
parsed.set_day(31)?;
parsed.set_month(12)?;
parsed.set_year(2014)?;
parsed.set_hour(4)?;
parsed.set_minute(26)?;
parsed.set_second(40)?;
parsed.set_offset(0)?;
let dt = parsed.to_datetime()?;
assert_eq!(dt.to_rfc2822(), "Wed, 31 Dec 2014 04:26:40 +0000");

let mut parsed = Parsed::new();
parsed.set_weekday(Weekday::Thu)?; // changed to the wrong day
parsed.set_day(31)?;
parsed.set_month(12)?;
parsed.set_year(2014)?;
parsed.set_hour(4)?;
parsed.set_minute(26)?;
parsed.set_second(40)?;
parsed.set_offset(0)?;
let result = parsed.to_datetime();

assert!(result.is_err());
if let Err(error) = result {
    assert_eq!(error.kind(), ParseErrorKind::Impossible);
}

The same using chrono’s build-in parser for RFC 2822 (the RFC2822 formatting item) and format::parse() showing how to inspect a field on failure.

use chrono::format::{parse, Fixed, Item, Parsed};
use chrono::Weekday;

let rfc_2822 = [Item::Fixed(Fixed::RFC2822)];

let mut parsed = Parsed::new();
parse(&mut parsed, "Wed, 31 Dec 2014 04:26:40 +0000", rfc_2822.iter())?;
let dt = parsed.to_datetime()?;

assert_eq!(dt.to_rfc2822(), "Wed, 31 Dec 2014 04:26:40 +0000");

let mut parsed = Parsed::new();
parse(&mut parsed, "Thu, 31 Dec 2014 04:26:40 +0000", rfc_2822.iter())?;
let result = parsed.to_datetime();

assert!(result.is_err());
if result.is_err() {
    // What is the weekday?
    assert_eq!(parsed.weekday(), Some(Weekday::Thu));
}

Implementations§

Source§

impl Parsed

Source

pub fn new() -> Parsed

Returns the initial value of parsed parts.

Source

pub fn set_year(&mut self, value: i64) -> ParseResult<()>

Set the year field to the given value.

The value can be negative, unlike the year_div_100 and year_mod_100 fields.

§Errors

Returns OUT_OF_RANGE if value is outside the range of an i32.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_year_div_100(&mut self, value: i64) -> ParseResult<()>

Set the year_div_100 field to the given value.

§Errors

Returns OUT_OF_RANGE if value is negative or if it is greater than i32::MAX.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_year_mod_100(&mut self, value: i64) -> ParseResult<()>

Set the year_mod_100 field to the given value.

When set it implies that the year is not negative.

If this field is set while the year_div_100 field is missing (and the full year field is also not set), it assumes a default value for the year_div_100 field. The default is 19 when year_mod_100 >= 70 and 20 otherwise.

§Errors

Returns OUT_OF_RANGE if value is negative or if it is greater than 99.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_isoyear(&mut self, value: i64) -> ParseResult<()>

Set the isoyear field, that is part of an ISO 8601 week date, to the given value.

The value can be negative, unlike the isoyear_div_100 and isoyear_mod_100 fields.

§Errors

Returns OUT_OF_RANGE if value is outside the range of an i32.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_isoyear_div_100(&mut self, value: i64) -> ParseResult<()>

Set the isoyear_div_100 field, that is part of an ISO 8601 week date, to the given value.

§Errors

Returns OUT_OF_RANGE if value is negative or if it is greater than i32::MAX.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_isoyear_mod_100(&mut self, value: i64) -> ParseResult<()>

Set the isoyear_mod_100 field, that is part of an ISO 8601 week date, to the given value.

When set it implies that the year is not negative.

If this field is set while the isoyear_div_100 field is missing (and the full isoyear field is also not set), it assumes a default value for the isoyear_div_100 field. The default is 19 when year_mod_100 >= 70 and 20 otherwise.

§Errors

Returns OUT_OF_RANGE if value is negative or if it is greater than 99.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_month(&mut self, value: i64) -> ParseResult<()>

Set the month field to the given value.

§Errors

Returns OUT_OF_RANGE if value is not in the range 1-12.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_week_from_sun(&mut self, value: i64) -> ParseResult<()>

Set the week_from_sun week number field to the given value.

Week 1 starts at the first Sunday of January.

§Errors

Returns OUT_OF_RANGE if value is not in the range 0-53.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_week_from_mon(&mut self, value: i64) -> ParseResult<()>

Set the week_from_mon week number field to the given value. Set the ‘week number starting with Monday’ field to the given value.

Week 1 starts at the first Monday of January.

§Errors

Returns OUT_OF_RANGE if value is not in the range 0-53.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_isoweek(&mut self, value: i64) -> ParseResult<()>

Set the isoweek field for an ISO 8601 week date to the given value.

§Errors

Returns OUT_OF_RANGE if value is not in the range 1-53.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_weekday(&mut self, value: Weekday) -> ParseResult<()>

Set the weekday field to the given value.

§Errors

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_ordinal(&mut self, value: i64) -> ParseResult<()>

Set the ordinal (day of the year) field to the given value.

§Errors

Returns OUT_OF_RANGE if value is not in the range 1-366.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_day(&mut self, value: i64) -> ParseResult<()>

Set the day of the month field to the given value.

§Errors

Returns OUT_OF_RANGE if value is not in the range 1-31.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_ampm(&mut self, value: bool) -> ParseResult<()>

Set the hour_div_12 am/pm field to the given value.

false indicates AM and true indicates PM.

§Errors

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_hour12(&mut self, value: i64) -> ParseResult<()>

Set the hour_mod_12 field, for the hour number in 12-hour clocks, to the given value.

Value must be in the canonical range of 1-12. It will internally be stored as 0-11 (value % 12).

§Errors

Returns OUT_OF_RANGE if value is not in the range 1-12.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_hour(&mut self, value: i64) -> ParseResult<()>

Set the hour_div_12 and hour_mod_12 fields to the given value for a 24-hour clock.

§Errors

May return OUT_OF_RANGE if value is not in the range 0-23. Currently only checks the value is not out of range for a u32.

Returns IMPOSSIBLE one of the fields was already set to a different value.

Source

pub fn set_minute(&mut self, value: i64) -> ParseResult<()>

Set the minute field to the given value.

§Errors

Returns OUT_OF_RANGE if value is not in the range 0-59.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_second(&mut self, value: i64) -> ParseResult<()>

Set the second field to the given value.

The value can be 60 in the case of a leap second.

§Errors

Returns OUT_OF_RANGE if value is not in the range 0-60.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_nanosecond(&mut self, value: i64) -> ParseResult<()>

Set the nanosecond field to the given value.

This is the number of nanoseconds since the whole second.

§Errors

Returns OUT_OF_RANGE if value is not in the range 0-999,999,999.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_timestamp(&mut self, value: i64) -> ParseResult<()>

Set the timestamp field to the given value.

A Unix timestamp is defined as the number of non-leap seconds since midnight UTC on January 1, 1970.

§Errors

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn set_offset(&mut self, value: i64) -> ParseResult<()>

Set the offset field to the given value.

The offset is in seconds from local time to UTC.

§Errors

Returns OUT_OF_RANGE if value is ouside the range of an i32.

Returns IMPOSSIBLE if this field was already set to a different value.

Source

pub fn to_naive_date(&self) -> ParseResult<NaiveDate>

Returns a parsed naive date out of given fields.

This method is able to determine the date from given subset of fields:

  • Year, month, day.
  • Year, day of the year (ordinal).
  • Year, week number counted from Sunday or Monday, day of the week.
  • ISO week date.

Gregorian year and ISO week date year can have their century number (*_div_100) omitted, the two-digit year is used to guess the century number then.

It checks all given date fields are consistent with each other.

§Errors

This method returns:

  • IMPOSSIBLE if any of the date fields conflict.
  • NOT_ENOUGH if there are not enough fields set in Parsed for a complete date.
  • OUT_OF_RANGE
    • if any of the date fields of Parsed are set to a value beyond their acceptable range.
    • if the value would be outside the range of a NaiveDate.
    • if the date does not exist.
Source

pub fn to_naive_time(&self) -> ParseResult<NaiveTime>

Returns a parsed naive time out of given fields.

This method is able to determine the time from given subset of fields:

  • Hour, minute. (second and nanosecond assumed to be 0)
  • Hour, minute, second. (nanosecond assumed to be 0)
  • Hour, minute, second, nanosecond.

It is able to handle leap seconds when given second is 60.

§Errors

This method returns:

  • OUT_OF_RANGE if any of the time fields of Parsed are set to a value beyond their acceptable range.
  • NOT_ENOUGH if an hour field is missing, if AM/PM is missing in a 12-hour clock, if minutes are missing, or if seconds are missing while the nanosecond field is present.
Source

pub fn to_naive_datetime_with_offset( &self, offset: i32, ) -> ParseResult<NaiveDateTime>

Returns a parsed naive date and time out of given fields, except for the offset field.

The offset is assumed to have a given value. It is not compared against the offset field set in the Parsed type, so it is allowed to be inconsistent.

This method is able to determine the combined date and time from date and time fields or from a single timestamp field. It checks all fields are consistent with each other.

§Errors

This method returns:

  • IMPOSSIBLE if any of the date fields conflict, or if a timestamp conflicts with any of the other fields.
  • NOT_ENOUGH if there are not enough fields set in Parsed for a complete datetime.
  • OUT_OF_RANGE
    • if any of the date or time fields of Parsed are set to a value beyond their acceptable range.
    • if the value would be outside the range of a NaiveDateTime.
    • if the date does not exist.
Source

pub fn to_fixed_offset(&self) -> ParseResult<FixedOffset>

Returns a parsed fixed time zone offset out of given fields.

§Errors

This method returns:

  • OUT_OF_RANGE if the offset is out of range for a FixedOffset.
  • NOT_ENOUGH if the offset field is not set.
Source

pub fn to_datetime(&self) -> ParseResult<DateTime<FixedOffset>>

Returns a parsed timezone-aware date and time out of given fields.

This method is able to determine the combined date and time from date, time and offset fields, and/or from a single timestamp field. It checks all fields are consistent with each other.

§Errors

This method returns:

  • IMPOSSIBLE if any of the date fields conflict, or if a timestamp conflicts with any of the other fields.
  • NOT_ENOUGH if there are not enough fields set in Parsed for a complete datetime including offset from UTC.
  • OUT_OF_RANGE
    • if any of the fields of Parsed are set to a value beyond their acceptable range.
    • if the value would be outside the range of a NaiveDateTime or FixedOffset.
    • if the date does not exist.
Source

pub fn to_datetime_with_timezone<Tz: TimeZone>( &self, tz: &Tz, ) -> ParseResult<DateTime<Tz>>

Returns a parsed timezone-aware date and time out of given fields, with an additional TimeZone used to interpret and validate the local date.

This method is able to determine the combined date and time from date and time, and/or from a single timestamp field. It checks all fields are consistent with each other.

If the parsed fields include an UTC offset, it also has to be consistent with the offset in the provided tz time zone for that datetime.

§Errors

This method returns:

  • IMPOSSIBLE
    • if any of the date fields conflict, if a timestamp conflicts with any of the other fields, or if the offset field is set but differs from the offset at that time in the tz time zone.
    • if the local datetime does not exists in the provided time zone (because it falls in a transition due to for example DST).
  • NOT_ENOUGH if there are not enough fields set in Parsed for a complete datetime, or if the local time in the provided time zone is ambiguous (because it falls in a transition due to for example DST) while there is no offset field or timestamp field set.
  • OUT_OF_RANGE
    • if the value would be outside the range of a NaiveDateTime or FixedOffset.
    • if any of the fields of Parsed are set to a value beyond their acceptable range.
    • if the date does not exist.
Source

pub fn year(&self) -> Option<i32>

Get the year field if set.

See also set_year().

Source

pub fn year_div_100(&self) -> Option<i32>

Get the year_div_100 field if set.

See also set_year_div_100().

Source

pub fn year_mod_100(&self) -> Option<i32>

Get the year_mod_100 field if set.

See also set_year_mod_100().

Source

pub fn isoyear(&self) -> Option<i32>

Get the isoyear field that is part of an ISO 8601 week date if set.

See also set_isoyear().

Source

pub fn isoyear_div_100(&self) -> Option<i32>

Get the isoyear_div_100 field that is part of an ISO 8601 week date if set.

See also set_isoyear_div_100().

Source

pub fn isoyear_mod_100(&self) -> Option<i32>

Get the isoyear_mod_100 field that is part of an ISO 8601 week date if set.

See also set_isoyear_mod_100().

Source

pub fn month(&self) -> Option<u32>

Get the month field if set.

See also set_month().

Source

pub fn week_from_sun(&self) -> Option<u32>

Get the week_from_sun field if set.

See also set_week_from_sun().

Source

pub fn week_from_mon(&self) -> Option<u32>

Get the week_from_mon field if set.

See also set_week_from_mon().

Source

pub fn isoweek(&self) -> Option<u32>

Get the isoweek field that is part of an ISO 8601 week date if set.

See also set_isoweek().

Source

pub fn weekday(&self) -> Option<Weekday>

Get the weekday field if set.

See also set_weekday().

Source

pub fn ordinal(&self) -> Option<u32>

Get the ordinal (day of the year) field if set.

See also set_ordinal().

Source

pub fn day(&self) -> Option<u32>

Get the day of the month field if set.

See also set_day().

Source

pub fn hour_div_12(&self) -> Option<u32>

Get the hour_div_12 field (am/pm) if set.

0 indicates AM and 1 indicates PM.

See also set_ampm() and set_hour().

Source

pub fn hour_mod_12(&self) -> Option<u32>

Get the hour_mod_12 field if set.

See also set_hour12() and set_hour().

Source

pub fn minute(&self) -> Option<u32>

Get the minute field if set.

See also set_minute().

Source

pub fn second(&self) -> Option<u32>

Get the second field if set.

See also set_second().

Source

pub fn nanosecond(&self) -> Option<u32>

Get the nanosecond field if set.

See also set_nanosecond().

Source

pub fn timestamp(&self) -> Option<i64>

Get the timestamp field if set.

See also set_timestamp().

Source

pub fn offset(&self) -> Option<i32>

Get the offset field if set.

See also set_offset().

Trait Implementations§

Source§

impl Clone for Parsed

Source§

fn clone(&self) -> Parsed

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Parsed

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for Parsed

Source§

fn default() -> Parsed

Returns the “default value” for a type. Read more
Source§

impl Hash for Parsed

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
Source§

impl PartialEq for Parsed

Source§

fn eq(&self, other: &Parsed) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Parsed

Source§

impl StructuralPartialEq for Parsed

Auto Trait Implementations§

§

impl Freeze for Parsed

§

impl RefUnwindSafe for Parsed

§

impl Send for Parsed

§

impl Sync for Parsed

§

impl Unpin for Parsed

§

impl UnwindSafe for Parsed

Blanket Implementations§

§

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

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

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

Mutably borrows from an owned value. Read more
§

impl<T> CloneToUninit for T
where T: Clone,

§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
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 T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

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

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

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

Performs the conversion.