Module icu::datetime::fieldset::dynamic

source ·
Expand description

Enumerations over field sets.

These enumerations can be used when the field set is not known at compile time. However, they may contribute negatively to the binary size of the formatters.

The most general type is CompositeFieldSet, which supports all field sets in a single enumeration. CompositeDateTimeFieldSet is a good choice when you don’t need to format time zones.

Summary of all the types:

TypeSupported Field Sets
DateFieldSetDate
CalendarPeriodFieldSetCalendar Period
TimeFieldSetTime
ZoneFieldSetZone
DateAndTimeFieldSetDate + Time
CompositeDateTimeFieldSetDate, Calendar Period, Time, Date + Time
CompositeFieldSetAll

§Examples

Format with the time display depending on a runtime boolean:

use icu::calendar::DateTime;
use icu::datetime::fieldset;
use icu::datetime::fieldset::dynamic::CompositeDateTimeFieldSet;
use icu::datetime::DateTimeFormatter;
use icu::locale::locale;
use writeable::TryWriteable;

fn get_field_set(should_display_time: bool) -> CompositeDateTimeFieldSet {
    if should_display_time {
        let field_set = fieldset::MDT::medium().hm();
        CompositeDateTimeFieldSet::DateTime(fieldset::dynamic::DateAndTimeFieldSet::MDT(field_set))
    } else {
        let field_set = fieldset::MD::medium();
        CompositeDateTimeFieldSet::Date(fieldset::dynamic::DateFieldSet::MD(field_set))
    }
}

let locale = locale!("en-US").into();
let datetime = DateTime::try_new_iso(2025, 1, 15, 16, 0, 0).unwrap();

let results = [true, false].map(get_field_set).map(|field_set| {
    DateTimeFormatter::try_new(&locale, field_set).unwrap()
}).map(|formatter| {
    formatter.convert_and_format(&datetime).try_write_to_string().unwrap().into_owned()
});

assert_eq!(results, ["Jan 15, 4:00 PM", "Jan 15"])

Enums§