Skip to main content

StrPTimeFmt

Struct StrPTimeFmt 

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

A pre-validated, reusable parse format for strptime-style directives.

Construct once with StrPTimeFmt::new or Dt::parse_fmt. On success the format is known to be syntactically valid for this crate’s parser, so later use will not fail because the format itself is unusable.

§What this type is for

  • Fail-fast format checking — catch unknown, unsupported, or truncated % directives at construction time (e.g. config load), not on every parse.
  • Reuse — store the validated format and call to_dt (or reformat helpers) many times without re-checking directive syntax.

§Guarantee

After new succeeds, parsing with this value (to_dt, and the parse step of to_str / to_str_b) will not fail with format-structure errors such as DtErrKind::UnknownItem, DtErrKind::UnsupportedItem, DtErrKind::TruncatedDirective, or DtErrKind::InvalidFractional.

Parsing can still fail for input reasons: mismatched literals, missing fields, out-of-range values, incomplete dates, trailing characters, bad offsets, and so on. See Dt::from_strptime.

§What this type is not

  • Not a speed optimization. Validation does not make strptime/strftime faster; it only checks the format once and stores a copy.
  • Not a print-format type. The stored string is the input (parse) pattern. Methods that take an output_fmt argument do not pre-validate that second format — only the format inside this struct is guaranteed.
  • Not the free-form auto-parser. For guessing formats from text, use Dt::from_str / the parse feature, not this type.

§Constraints

  • Format must be ASCII only.
  • Format length must be ≤ MAX_FMT_LEN (256 bytes).
  • Bytes are copied into an owned fixed-size buffer (no heap allocation).
  • Directives match the parse grammar documented on Dt::from_strptime (including library extensions such as %L, %*, %J, %Q). Printer-only spellings (e.g. trim flag ~ in %.~f) are not accepted here.

§Examples

use deep_time::{Dt, StrPTimeFmt};

// Prefer validating once (e.g. at startup) then reusing.
let fmt = StrPTimeFmt::new("%Y-%m-%d %H:%M:%S").unwrap();
// equivalent: Dt::parse_fmt("%Y-%m-%d %H:%M:%S").unwrap();

let dt = fmt.to_dt("2025-05-23 14:30:00", false, false, false).unwrap();
assert_eq!(dt.to_ymd().yr(), 2025);

// Construction fails on a broken format — before any input is parsed.
assert!(StrPTimeFmt::new("%Y-%m-%").is_err());
assert!(StrPTimeFmt::new("%c").is_err()); // unsupported locale directive

§See also

Implementations§

Source§

impl StrPTimeFmt

Source

pub const MAX_FMT_LEN: usize = 256

Maximum length of a format string in bytes (not characters).

Longer strings are rejected with DtErrKind::InvalidLen at construction.

Source

pub fn new(fmt: &str) -> Result<Self, DtErr>

Validates a strptime-style format and stores it for reuse.

On success, the returned value carries the guarantee described on StrPTimeFmt: the format will not fail later for structural reasons when used to parse.

Accepts the same % directives and extensions as Dt::from_strptime (one optional flag -/_/0/^/#, optional width digits, up to three colons for offsets, and %.f / %.N fractional forms).

§Errors
§Examples
use deep_time::StrPTimeFmt;

let fmt = StrPTimeFmt::new("%F %T").unwrap();
let dt = fmt.to_dt("2025-05-23 14:30:00", false, false, false).unwrap();
assert_eq!(dt.to_ymd().day(), 23);
Source

pub fn to_dt( &self, s: &str, inp_can_end_before_fmt: bool, fmt_can_end_before_inp: bool, allow_partial_date: bool, ) -> Result<Dt, DtErr>

Parses s with this format and converts the result to a Dt.

Equivalent to Dt::from_strptime(s, fmt, …) where fmt is the string validated at construction — except the format has already been checked, so failures should only reflect the input (or post-parse conversion), not broken directive syntax.

§Parameters
  • s: The input string to parse.
  • inp_can_end_before_fmt: Allow input to end before the format is fully consumed (parse what is present, ignore remaining directives).
  • fmt_can_end_before_inp: Allow the format to end before the input is fully consumed (trailing characters in s are OK).
  • allow_partial_date: Default missing month/day to 1 instead of returning DtErrKind::Incomplete.

Full directive list and flag semantics: Dt::from_strptime.

§Errors

Same input and conversion errors as Dt::from_strptime (mismatch, expected fields, out of range, trailing characters, incomplete date, timezone issues, etc.). Format-structure errors for the stored pattern are not expected after a successful new.

§Examples
use deep_time::StrPTimeFmt;

let fmt = StrPTimeFmt::new("%F %T").unwrap();
let dt = fmt.to_dt("2025-05-23 14:30:00", false, false, false).unwrap();
assert_eq!(dt.to_ymd().hr(), 14);
Source

pub fn to_str( &self, s: &str, output_fmt: &str, inp_can_end_before_fmt: bool, fmt_can_end_before_inp: bool, allow_partial_date: bool, lang: Lang, ) -> Result<String, DtErr>

Parse s with this format, then format the resulting Dt with output_fmt into an owned String.

Requires the alloc feature. Prefer to_str_b when you want a fixed stack buffer and no allocator.

Important: only the format stored in self is pre-validated. output_fmt is passed straight to formatting and may fail with format-structure errors (truncated %, unknown directives, etc.) if it is invalid. Validate it separately with StrPTimeFmt::new if you need the same guarantee for a parse pattern (some print-only spellings are still rejected by new).

§Parameters
  • s: Input datetime string, parsed with self.
  • output_fmt: Format string for the output (not pre-validated).
  • inp_can_end_before_fmt, fmt_can_end_before_inp, allow_partial_date: passed through to to_dt.
  • lang: Language for weekday/month names in the output.
§Examples
use deep_time::{Lang, StrPTimeFmt};

let fmt = StrPTimeFmt::new("%Y-%m-%dT%H:%M:%S").unwrap();
let s = fmt
    .to_str("2000-01-01T12:00:00", "%d %m %Y %H:%M:%S", false, false, false, Lang::En)
    .unwrap();
assert_eq!(s, "01 01 2000 12:00:00");
Source

pub fn to_str_b( &self, s: &str, output_fmt: &str, inp_can_end_before_fmt: bool, fmt_can_end_before_inp: bool, allow_partial_date: bool, lang: Lang, ) -> Result<BufStr<STRTIME_SIZE>, DtErr>

Parse s with this format, then format the resulting Dt with output_fmt into a stack BufStr.

Same pipeline as to_str, without requiring alloc.

Important: only the format stored in self is pre-validated. output_fmt is not checked at construction of this value and may fail if it contains invalid or unsupported directives. See to_str for details.

§Parameters
  • s: Input datetime string, parsed with self.
  • output_fmt: Format string for the output (not pre-validated).
  • inp_can_end_before_fmt, fmt_can_end_before_inp, allow_partial_date: passed through to to_dt.
  • lang: Language for weekday/month names in the output.
§Examples
use deep_time::{Lang, StrPTimeFmt};

let fmt = StrPTimeFmt::new("%Y-%m-%dT%H:%M:%S").unwrap();
let s = fmt
    .to_str_b("2000-01-01T12:00:00", "%d %m %Y %H:%M:%S", false, false, false, Lang::En)
    .unwrap();
assert_eq!(s.as_str(), "01 01 2000 12:00:00");

Trait Implementations§

Source§

impl Clone for StrPTimeFmt

Source§

fn clone(&self) -> StrPTimeFmt

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for StrPTimeFmt

Source§

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

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

impl Format for StrPTimeFmt

Available on crate feature defmt only.
Source§

fn format(&self, f: Formatter<'_>)

Writes the defmt representation of self to fmt.

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

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

Source§

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

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

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

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

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

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

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more