pub struct ZonedDateTimeFormatter(_, _);
Expand description

ZonedDateTimeFormatter is a formatter capable of formatting date/times with time zones from any calendar, selected at runtime. For the difference between this and TypedZonedDateTimeFormatter, please read the crate root docs.

This is equivalently the composition of DateTimeFormatter and TimeZoneFormatter.

ZonedDateTimeFormatter uses data from the [data provider]s, the selected DataLocale, and the provided pattern to collect all data necessary to format a datetime with time zones into that locale.

The various pattern symbols specified in UTS-35 require different sets of data for formatting. As such, TimeZoneFormatter will pull in only the resources it needs to format that pattern that is derived from the provided DateTimeFormatterOptions.

For that reason, one should think of the process of formatting a zoned datetime in two steps: first, a computationally heavy construction of ZonedDateTimeFormatter, and then fast formatting of the data using the instance.

Examples

Using a GMT time zone:

use icu::calendar::{DateTime, Gregorian};
use icu::datetime::{options::length, ZonedDateTimeFormatter};
use icu::locid::locale;
use icu::timezone::CustomTimeZone;
use writeable::assert_writeable_eq;

let options = length::Bag::from_date_time_style(
    length::Date::Medium,
    length::Time::Long,
);
let zdtf = ZonedDateTimeFormatter::try_new_unstable(
    &icu_testdata::unstable(),
    &locale!("en").into(),
    options.into(),
    Default::default(),
)
.expect("Failed to create ZonedDateTimeFormatter instance.");

let datetime = DateTime::try_new_iso_datetime(2020, 9, 1, 12, 34, 28)
    .expect("Failed to construct DateTime.");
let any_datetime = datetime.to_any();

let time_zone = CustomTimeZone::utc();

assert_writeable_eq!(
    zdtf.format(&any_datetime, &time_zone)
        .expect("Calendars should match"),
    "Sep 1, 2020, 12:34:28 PM GMT"
);

Using a non-GMT time zone, specified by id:

use icu::calendar::{DateTime, Gregorian};
use icu::datetime::{options::length, ZonedDateTimeFormatter};
use icu::locid::locale;
use icu::timezone::{CustomTimeZone, GmtOffset, MetazoneCalculator, ZoneVariant};
use tinystr::TinyAsciiStr;
use writeable::assert_writeable_eq;

let options = length::Bag::from_date_time_style(
    length::Date::Medium,
    length::Time::Full,
);
let zdtf = ZonedDateTimeFormatter::try_new_unstable(
    &icu_testdata::unstable(),
    &locale!("en").into(),
    options.into(),
    Default::default(),
)
.expect("Failed to create ZonedDateTimeFormatter instance.");

// Create a DateTime at September 1, 2020 at 12:34:28 PM
let datetime = DateTime::try_new_iso_datetime(2020, 9, 1, 12, 34, 28)
    .expect("Failed to construct DateTime.");
let any_datetime = datetime.to_any();

// Create a time zone for America/Chicago at GMT-6:
let mut time_zone = CustomTimeZone::new_empty();
time_zone.gmt_offset = "-06:00".parse::<GmtOffset>().ok();
time_zone.time_zone_id = "uschi".parse::<TinyAsciiStr<8>>().ok().map(Into::into);
time_zone.zone_variant = Some(ZoneVariant::daylight());

// Compute the metazone during `datetime` (September 1, 2020 at 12:34:28 PM):
let mzc = MetazoneCalculator::try_new_unstable(&icu_testdata::unstable()).unwrap();
time_zone.maybe_calculate_metazone(&mzc, &datetime);

assert_writeable_eq!(
    zdtf
      .format(&any_datetime, &time_zone)
      .expect("Calendars should match"),
    "Sep 1, 2020, 12:34:28 PM Central Daylight Time");

Implementations§

source§

impl ZonedDateTimeFormatter

source

pub fn try_new_experimental_unstable<P>( provider: &P, locale: &DataLocale, date_time_format_options: DateTimeFormatterOptions, time_zone_format_options: TimeZoneFormatterOptions ) -> Result<Self, DateTimeError>where P: DataProvider<TimeSymbolsV1Marker> + DataProvider<TimeLengthsV1Marker> + DataProvider<DateSkeletonPatternsV1Marker> + DataProvider<WeekDataV1Marker> + DataProvider<TimeZoneFormatsV1Marker> + DataProvider<ExemplarCitiesV1Marker> + DataProvider<MetazoneGenericNamesLongV1Marker> + DataProvider<MetazoneGenericNamesShortV1Marker> + DataProvider<MetazoneSpecificNamesLongV1Marker> + DataProvider<MetazoneSpecificNamesShortV1Marker> + DataProvider<OrdinalV1Marker> + DataProvider<DecimalSymbolsV1Marker> + DataProvider<GregorianDateLengthsV1Marker> + DataProvider<BuddhistDateLengthsV1Marker> + DataProvider<JapaneseDateLengthsV1Marker> + DataProvider<JapaneseExtendedDateLengthsV1Marker> + DataProvider<CopticDateLengthsV1Marker> + DataProvider<IndianDateLengthsV1Marker> + DataProvider<EthiopianDateLengthsV1Marker> + DataProvider<GregorianDateSymbolsV1Marker> + DataProvider<BuddhistDateSymbolsV1Marker> + DataProvider<JapaneseDateSymbolsV1Marker> + DataProvider<JapaneseExtendedDateSymbolsV1Marker> + DataProvider<CopticDateSymbolsV1Marker> + DataProvider<IndianDateSymbolsV1Marker> + DataProvider<EthiopianDateSymbolsV1Marker> + DataProvider<JapaneseErasV1Marker> + DataProvider<JapaneseExtendedErasV1Marker> + ?Sized,

Constructor that takes a selected DataLocale, a reference to a data provider for dates, a data provider for time zones, a data provider for calendars, and a list of DateTimeFormatterOptions. It collects all data necessary to format zoned datetime values into the given locale.

This method is unstable, more bounds may be added in the future as calendar support is added. It is preferable to use a provider that implements DataProvider<D> for all D, and ensure data is loaded as appropriate. The Self::try_new_with_buffer_provider(), Self::try_new_with_any_provider() constructors may also be used if compile stability is desired.

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.

🚧 This code is experimental; it may change at any time, in breaking or non-breaking ways, including in SemVer minor releases. It can be enabled with the "experimental" Cargo feature of the icu meta-crate. Use with caution. #1317
Examples
use icu::calendar::{DateTime, Gregorian};
use icu::datetime::options::components;
use icu::datetime::{DateTimeFormatterOptions, ZonedDateTimeFormatter};
use icu::locid::locale;
use icu::timezone::CustomTimeZone;
use icu_provider::AsDeserializingBufferProvider;
use std::str::FromStr;
use writeable::assert_writeable_eq;

let mut options = components::Bag::default();
options.year = Some(components::Year::Numeric);
options.month = Some(components::Month::Long);
options.hour = Some(components::Numeric::Numeric);
options.minute = Some(components::Numeric::Numeric);
options.time_zone_name = Some(components::TimeZoneName::GmtOffset);

let zdtf = ZonedDateTimeFormatter::try_new_experimental_unstable(
    &icu_testdata::buffer().as_deserializing(),
    &locale!("en-u-ca-gregory").into(),
    options.into(),
    Default::default(),
)
.expect("Construction should succeed");

let datetime =
    DateTime::try_new_iso_datetime(2021, 04, 08, 16, 12, 37).unwrap();
let time_zone = CustomTimeZone::from_str("-07:00").unwrap();
let any_datetime = datetime.to_any();

assert_writeable_eq!(
    zdtf.format(&any_datetime, &time_zone).unwrap(),
    "April 2021, 16:12 GMT-07:00"
);
source

pub fn try_new_unstable<P>( provider: &P, locale: &DataLocale, date_time_format_options: DateTimeFormatterOptions, time_zone_format_options: TimeZoneFormatterOptions ) -> Result<Self, DateTimeError>where P: DataProvider<TimeSymbolsV1Marker> + DataProvider<TimeLengthsV1Marker> + DataProvider<WeekDataV1Marker> + DataProvider<TimeZoneFormatsV1Marker> + DataProvider<ExemplarCitiesV1Marker> + DataProvider<MetazoneGenericNamesLongV1Marker> + DataProvider<MetazoneGenericNamesShortV1Marker> + DataProvider<MetazoneSpecificNamesLongV1Marker> + DataProvider<MetazoneSpecificNamesShortV1Marker> + DataProvider<OrdinalV1Marker> + DataProvider<DecimalSymbolsV1Marker> + DataProvider<GregorianDateLengthsV1Marker> + DataProvider<BuddhistDateLengthsV1Marker> + DataProvider<JapaneseDateLengthsV1Marker> + DataProvider<JapaneseExtendedDateLengthsV1Marker> + DataProvider<CopticDateLengthsV1Marker> + DataProvider<IndianDateLengthsV1Marker> + DataProvider<EthiopianDateLengthsV1Marker> + DataProvider<GregorianDateSymbolsV1Marker> + DataProvider<BuddhistDateSymbolsV1Marker> + DataProvider<JapaneseDateSymbolsV1Marker> + DataProvider<JapaneseExtendedDateSymbolsV1Marker> + DataProvider<CopticDateSymbolsV1Marker> + DataProvider<IndianDateSymbolsV1Marker> + DataProvider<EthiopianDateSymbolsV1Marker> + DataProvider<JapaneseErasV1Marker> + DataProvider<JapaneseExtendedErasV1Marker> + ?Sized,

Constructor that takes a selected DataLocale, a reference to a data provider for dates, a data provider for time zones, a data provider for calendars, and a list of DateTimeFormatterOptions. It collects all data necessary to format zoned datetime values into the given locale.

This method is unstable, more bounds may be added in the future as calendar support is added. It is preferable to use a provider that implements DataProvider<D> for all D, and ensure data is loaded as appropriate. The Self::try_new_with_buffer_provider(), Self::try_new_with_any_provider() constructors may also be used if compile stability is desired.

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.

Examples
use icu::calendar::{DateTime, Gregorian};
use icu::datetime::options::length;
use icu::datetime::time_zone::TimeZoneFormatterOptions;
use icu::datetime::{DateTimeFormatterOptions, ZonedDateTimeFormatter};
use icu::locid::locale;
use icu::timezone::CustomTimeZone;
use std::str::FromStr;
use writeable::assert_writeable_eq;

let options = length::Bag::from_date_time_style(
    length::Date::Medium,
    length::Time::Long,
);
let locale = locale!("en-u-ca-gregory");

let zdtf = ZonedDateTimeFormatter::try_new_unstable(
    &icu_testdata::unstable(),
    &locale.into(),
    options.into(),
    TimeZoneFormatterOptions::default(),
)
.expect("Construction should succeed");

let datetime =
    DateTime::try_new_iso_datetime(2021, 04, 08, 16, 12, 37).unwrap();
let time_zone = CustomTimeZone::from_str("-07:00").unwrap();
let any_datetime = datetime.to_any();

assert_writeable_eq!(
    zdtf.format(&any_datetime, &time_zone).unwrap(),
    "Apr 8, 2021, 4:12:37 PM GMT-07:00"
);
source

pub fn try_new_with_any_provider<P>( data_provider: &P, locale: &DataLocale, options: DateTimeFormatterOptions, time_zone_format_options: TimeZoneFormatterOptions ) -> Result<Self, DateTimeError>where P: AnyProvider,

Construct a new ZonedDateTimeFormatter from a data provider that implements AnyProvider.

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.

The provider must be able to provide data for the following keys: datetime/symbols@1, datetime/timelengths@1, datetime/timelengths@1, datetime/symbols@1, datetime/skeletons@1, datetime/week_data@1, plurals/ordinals@1, time_zone/formats@1, time_zone/exemplar_cities@1, time_zone/generic_long@1, time_zone/generic_short@1, time_zone/specific_long@1, time_zone/specific_short@1, time_zone/metazone_period@1.

Furthermore, based on the type of calendar used, one of the following data keys may be necessary:

  • u-ca-japanese (Japanese calendar): calendar/japanese@1

Test will currently fail due to https://github.com/unicode-org/icu4x/issues/2188, since these functions currently must be given a fallback-enabled provider and we do not have one in icu_testdata

use icu::calendar::{DateTime, Gregorian};
use icu::datetime::options::length;
use icu::datetime::{DateTimeFormatterOptions, ZonedDateTimeFormatter};
use icu::locid::locale;
use icu::timezone::CustomTimeZone;
use std::str::FromStr;
use writeable::assert_writeable_eq;

let options = length::Bag::from_date_time_style(length::Date::Medium, length::Time::Long).into();
let locale = locale!("en-u-ca-gregory");

let zdtf = ZonedDateTimeFormatter::try_new_with_any_provider(
    &icu_testdata::any(),
    &locale.into(),
    options,
    Default::default(),
)
.expect("Construction should succeed");

let datetime = DateTime::try_new_iso_datetime(2021, 04, 08, 16, 12, 37).unwrap();
let time_zone = CustomTimeZone::from_str("-07:00").unwrap();
let any_datetime = datetime.to_any();

assert_writeable_eq!(
    zdtf.format(&any_datetime, &time_zone).unwrap(),
    "Apr 8, 2021, 4:12:37 PM GMT-07:00"
);
source

pub fn try_new_with_buffer_provider<P>( data_provider: &P, locale: &DataLocale, options: DateTimeFormatterOptions, time_zone_format_options: TimeZoneFormatterOptions ) -> Result<Self, DateTimeError>where P: BufferProvider,

Construct a new ZonedDateTimeFormatter from a data provider that implements BufferProvider.

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.

The provider must be able to provide data for the following keys: datetime/symbols@1, datetime/timelengths@1, datetime/timelengths@1, datetime/symbols@1, datetime/skeletons@1, datetime/week_data@1, plurals/ordinals@1, time_zone/formats@1, time_zone/exemplar_cities@1, time_zone/generic_long@1, time_zone/generic_short@1, time_zone/specific_long@1, time_zone/specific_short@1, time_zone/metazone_period@1.

Furthermore, based on the type of calendar used, one of the following data keys may be necessary:

  • u-ca-japanese (Japanese calendar): calendar/japanese@1
use icu::calendar::{DateTime, Gregorian};
use icu::datetime::options::length;
use icu::datetime::{DateTimeFormatterOptions, ZonedDateTimeFormatter};
use icu::locid::locale;
use icu::timezone::CustomTimeZone;
use std::str::FromStr;
use writeable::assert_writeable_eq;

let options = length::Bag::from_date_time_style(
    length::Date::Medium,
    length::Time::Long,
)
.into();
let locale = locale!("en");

let zdtf = ZonedDateTimeFormatter::try_new_with_buffer_provider(
    &icu_testdata::buffer(),
    &locale.into(),
    options,
    Default::default(),
)
.expect("Construction should succeed");

let datetime =
    DateTime::try_new_iso_datetime(2021, 04, 08, 16, 12, 37).unwrap();
let time_zone = CustomTimeZone::from_str("-07:00").unwrap();
let any_datetime = datetime.to_any();

assert_writeable_eq!(
    zdtf.format(&any_datetime, &time_zone).unwrap(),
    "Apr 8, 2021, 4:12:37 PM GMT-07:00"
);
source

pub fn format<'l>( &'l self, date: &impl DateTimeInput<Calendar = AnyCalendar>, time_zone: &impl TimeZoneInput ) -> Result<FormattedZonedDateTime<'l>, DateTimeError>

Takes a DateTimeInput and a TimeZoneInput and returns an instance of a FormattedZonedDateTime that contains all information necessary to display a formatted date and operate on it.

This function will fail if the date passed in uses a different calendar than that of the AnyCalendar. Please convert dates before passing them in if necessary. This function will automatically convert and format dates that are associated with the ISO calendar.

source

pub fn format_to_string( &self, date: &impl DateTimeInput<Calendar = AnyCalendar>, time_zone: &impl TimeZoneInput ) -> Result<String, DateTimeError>

Takes a DateTimeInput and a TimeZoneInput and returns it formatted as a string.

This function will fail if the date passed in uses a different calendar than that of the AnyCalendar. Please convert dates before passing them in if necessary. This function will automatically convert and format dates that are associated with the ISO calendar.

Trait Implementations§

source§

impl Debug for ZonedDateTimeFormatter

source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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 Twhere 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, U> TryFrom<U> for Twhere U: Into<T>,

§

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 Twhere U: TryFrom<T>,

§

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 Twhere T: 'static,

source§

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