Struct icu_datetime::DateTimeFormatter

source ·
pub struct DateTimeFormatter<FSet: DateTimeNamesMarker> { /* private fields */ }
Expand description

DateTimeFormatter is a formatter capable of formatting dates and/or times from a calendar selected at runtime.

For more details, please read the crate root docs.

📏 This item has a stack size of 400 bytes on the stable toolchain at release date.

Implementations§

source§

impl<FSet> DateTimeFormatter<FSet>

source

pub fn try_new( prefs: DateTimeFormatterPreferences, field_set: FSet, ) -> Result<Self, DateTimeFormatterLoadError>

Creates a new DateTimeFormatter from compiled data with datetime components specified at build time.

This method will pick the calendar off of the locale; and if unspecified or unknown will fall back to the default calendar for the locale. See AnyCalendarKind for a list of supported calendars.

Use this constructor for optimal data size and memory use if you know the required datetime components at build time. If you do not know the datetime components until runtime, use a with_components constructor.

Enabled with the compiled_data Cargo feature.

📚 Help choosing a constructor

§Examples

Basic usage:

use icu::calendar::{any_calendar::AnyCalendar, DateTime};
use icu::datetime::fieldsets::YMD;
use icu::datetime::DateTimeFormatter;
use icu::locale::locale;
use std::str::FromStr;
use writeable::assert_writeable_eq;

let formatter = DateTimeFormatter::try_new(
    locale!("en-u-ca-hebrew").into(),
    YMD::medium(),
)
.unwrap();

let datetime = DateTime::try_new_iso(2024, 5, 8, 0, 0, 0).unwrap();

assert_writeable_eq!(
    formatter.format_any_calendar(&datetime),
    "30 Nisan 5784"
);
source

pub fn try_new_with_any_provider<P>( provider: &P, prefs: DateTimeFormatterPreferences, field_set: FSet, ) -> Result<Self, DateTimeFormatterLoadError>
where P: AnyProvider + ?Sized,

A version of [Self :: try_new] that uses custom data provided by an AnyProvider.

📚 Help choosing a constructor

source

pub fn try_new_with_buffer_provider<P>( provider: &P, prefs: DateTimeFormatterPreferences, field_set: FSet, ) -> Result<Self, DateTimeFormatterLoadError>
where P: BufferProvider + ?Sized,

A version of [Self :: try_new] that uses custom data provided by a BufferProvider.

Enabled with the serde feature.

📚 Help choosing a constructor

source

pub fn try_new_unstable<P>( provider: &P, prefs: DateTimeFormatterPreferences, field_set: FSet, ) -> Result<Self, DateTimeFormatterLoadError>

A version of Self::try_new that uses custom data provided by a DataProvider.

📚 Help choosing a constructor

⚠️ The bounds on provider may change over time, including in SemVer minor releases.
source§

impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet>
where FSet::D: DateInputMarkers, FSet::T: TimeMarkers, FSet::Z: ZoneMarkers,

source

pub fn format_same_calendar<I>( &self, datetime: &I, ) -> Result<FormattedDateTime<'_>, MismatchedCalendarError>
where I: ?Sized + InSameCalendar + AllInputMarkers<FSet>,

Formats a datetime, checking that the calendar system is correct.

If the datetime is not in the same calendar system as the formatter, an error is returned.

§Examples

Mismatched calendars will return an error:

use icu::calendar::Date;
use icu::datetime::fieldsets::YMD;
use icu::datetime::DateTimeFormatter;
use icu::datetime::MismatchedCalendarError;
use icu::locale::locale;

let formatter = DateTimeFormatter::try_new(
    locale!("en-u-ca-hebrew").into(),
    YMD::long(),
)
.unwrap();

let date = Date::try_new_gregorian(2023, 12, 20).unwrap();

assert!(matches!(
    formatter.format_same_calendar(&date),
    Err(MismatchedCalendarError { .. })
));

A time cannot be passed into the formatter when a date is expected:

use icu::calendar::Time;
use icu::datetime::DateTimeFormatter;
use icu::datetime::fieldsets::YMD;
use icu::locale::locale;

let formatter = DateTimeFormatter::try_new(
    locale!("es-MX").into(),
    Length::Long.into(),
)
.unwrap();

// the trait `GetField<AnyCalendarKind>`
// is not implemented for `icu::icu_calendar::Time`
formatter.format_same_calendar(&Time::try_new(0, 0, 0, 0).unwrap());
source

pub fn format_any_calendar<'a, I>( &'a self, datetime: &I, ) -> FormattedDateTime<'a>
where I: ?Sized + ConvertCalendar, I::Converted<'a>: Sized + AllInputMarkers<FSet>,

Formats a datetime after first converting it to the formatter’s calendar.

§Examples

Mismatched calendars convert and format automatically:

use icu::calendar::Date;
use icu::datetime::fieldsets::YMD;
use icu::datetime::DateTimeFormatter;
use icu::datetime::MismatchedCalendarError;
use icu::locale::locale;
use writeable::assert_writeable_eq;

let formatter = DateTimeFormatter::try_new(
    locale!("en-u-ca-hebrew").into(),
    YMD::long(),
)
.unwrap();

let date = Date::try_new_roc(113, 5, 8).unwrap();

assert_writeable_eq!(formatter.format_any_calendar(&date), "30 Nisan 5784");

A time cannot be passed into the formatter when a date is expected:

use icu::calendar::Time;
use icu::datetime::DateTimeFormatter;
use icu::datetime::fieldsets::YMD;
use icu::locale::locale;

let formatter = DateTimeFormatter::try_new(
    locale!("es-MX").into(),
    Length::Long.into(),
)
.unwrap();

// the trait `GetField<AnyCalendarKind>`
// is not implemented for `icu::icu_calendar::Time`
formatter.format_any_calendar(&Time::try_new(0, 0, 0, 0).unwrap());
source§

impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet>

source

pub fn try_into_typed_formatter<C>( self, ) -> Result<FixedCalendarDateTimeFormatter<C, FSet>, MismatchedCalendarError>
where C: CldrCalendar + IntoAnyCalendar,

Attempt to convert this DateTimeFormatter into one with a specific calendar.

Returns an error if the type parameter does not match the inner calendar.

§Examples
use icu::calendar::cal::Hebrew;
use icu::calendar::Date;
use icu::datetime::fieldsets::YMD;
use icu::datetime::DateTimeFormatter;
use icu::locale::locale;
use writeable::assert_writeable_eq;

let formatter = DateTimeFormatter::try_new(
    locale!("en-u-ca-hebrew").into(),
    YMD::long(),
)
.unwrap()
.try_into_typed_formatter::<Hebrew>()
.unwrap();

let date = Date::try_new_hebrew(5785, 1, 12).unwrap();

assert_writeable_eq!(formatter.format(&date), "12 Tishri 5785");

An error occurs if the calendars don’t match:

use icu::calendar::cal::Hebrew;
use icu::calendar::Date;
use icu::datetime::fieldsets::YMD;
use icu::datetime::DateTimeFormatter;
use icu::datetime::MismatchedCalendarError;
use icu::locale::locale;

let result = DateTimeFormatter::try_new(
    locale!("en-u-ca-buddhist").into(),
    YMD::long(),
)
.unwrap()
.try_into_typed_formatter::<Hebrew>();

assert!(matches!(result, Err(MismatchedCalendarError { .. })));
source

pub fn with_fset<FSet2: DateTimeNamesFrom<FSet>>( self, ) -> DateTimeFormatter<FSet2>

Maps a DateTimeFormatter of a specific FSet to a more general FSet.

For example, this can transform a formatter for YMD to one for DateFieldSet.

§Examples
use icu::calendar::Gregorian;
use icu::calendar::DateTime;
use icu::datetime::DateTimeFormatter;
use icu::datetime::fieldsets::{YMD, enums::DateFieldSet};
use icu::locale::locale;
use writeable::assert_writeable_eq;

let specific_formatter = DateTimeFormatter::try_new(
    locale!("fr").into(),
    YMD::medium(),
)
.unwrap();

// Test that the specific formatter works:
let datetime = DateTime::try_new_gregorian(2024, 12, 20, 14, 30, 0).unwrap();
assert_writeable_eq!(
    specific_formatter.format_any_calendar(&datetime),
    "20 déc. 2024"
);

// Make a more general formatter:
let general_formatter = specific_formatter.with_fset::<DateFieldSet>();

// Test that it still works:
assert_writeable_eq!(
    general_formatter.format_any_calendar(&datetime),
    "20 déc. 2024"
);
source

pub fn calendar_kind(&self) -> AnyCalendarKind

Returns the calendar system used in this formatter.

§Examples
use icu::calendar::AnyCalendarKind;
use icu::calendar::Date;
use icu::datetime::fieldsets::YMD;
use icu::datetime::DateTimeFormatter;
use icu::locale::locale;
use writeable::assert_writeable_eq;

let formatter = DateTimeFormatter::try_new(
    locale!("th").into(),
    YMD::long(),
)
.unwrap();

assert_writeable_eq!(
    formatter.format_any_calendar(&Date::try_new_iso(2024, 12, 16).unwrap()),
    "16 ธันวาคม 2567"
);

assert_eq!(formatter.calendar_kind(), AnyCalendarKind::Buddhist);
assert_eq!(formatter.calendar_kind().as_bcp47_string(), "buddhist");

Trait Implementations§

source§

impl<FSet: Debug + DateTimeNamesMarker> Debug for DateTimeFormatter<FSet>

source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<FSet> Freeze for DateTimeFormatter<FSet>

§

impl<FSet> RefUnwindSafe for DateTimeFormatter<FSet>

§

impl<FSet> Send for DateTimeFormatter<FSet>

§

impl<FSet> Sync for DateTimeFormatter<FSet>

§

impl<FSet> Unpin for DateTimeFormatter<FSet>

§

impl<FSet> UnwindSafe for DateTimeFormatter<FSet>

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> 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> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. 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.
§

impl<T> ErasedDestructor for T
where T: 'static,

§

impl<T> MaybeSendSync for T
where T: Send + Sync,