1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use crate::provider::date_time::PatternForLengthError;
#[cfg(feature = "experimental")]
use crate::provider::date_time::UnsupportedOptionsOrDataOrPatternError;
use crate::{calendar, options::DateTimeFormatterOptions, raw};
use alloc::string::String;
use icu_provider::prelude::*;
use crate::helpers::size_test;
use crate::input::{DateTimeInput, ExtractedDateTimeInput, TimeZoneInput};
use crate::provider::{self, calendar::*, date_time::PatternSelector};
use crate::time_zone::TimeZoneFormatterOptions;
use crate::{DateTimeError, FormattedZonedDateTime};
use icu_calendar::any_calendar::{AnyCalendar, AnyCalendarKind};
use icu_calendar::provider::{
ChineseCacheV1Marker, DangiCacheV1Marker, IslamicObservationalCacheV1Marker,
IslamicUmmAlQuraCacheV1Marker, JapaneseErasV1Marker, JapaneseExtendedErasV1Marker,
WeekDataV1Marker,
};
use icu_calendar::{DateTime, Time};
use icu_decimal::provider::DecimalSymbolsV1Marker;
use icu_plurals::provider::OrdinalV1Marker;
use writeable::Writeable;
size_test!(ZonedDateTimeFormatter, zoned_date_time_formatter_size, 6248);
/// [`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`](crate::TypedZonedDateTimeFormatter),
/// please read the [crate root docs][crate].
///
/// This is equivalently the composition of
/// [`DateTimeFormatter`](crate::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.
#[doc = zoned_date_time_formatter_size!()]
///
/// # Examples
///
/// Using a GMT time zone:
///
/// ```
/// use icu::calendar::DateTime;
/// 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(
/// &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;
/// 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(
/// &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::new();
/// 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");
/// ```
///
/// [`TimeZoneFormatter`]: crate::time_zone::TimeZoneFormatter
#[derive(Debug)]
pub struct ZonedDateTimeFormatter(raw::ZonedDateTimeFormatter, AnyCalendar);
impl ZonedDateTimeFormatter {
/// Constructor that takes a selected [`DataLocale`] and a list of [`DateTimeFormatterOptions`] and uses compiled data.
/// It collects all data necessary to format zoned datetime values into the given locale.
///
/// 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.
///
/// ✨ *Enabled with the `compiled_data` and `experimental` Cargo features.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
///
/// <div class="stab unstable">
/// 🚧 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.
/// <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
/// </div>
///
/// # Examples
///
/// ```
/// use icu::calendar::DateTime;
/// use icu::datetime::options::components;
/// use icu::datetime::ZonedDateTimeFormatter;
/// use icu::locid::locale;
/// use icu::timezone::CustomTimeZone;
/// 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(
/// &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"
/// );
/// ```
#[cfg(feature = "experimental")]
#[cfg(feature = "compiled_data")]
pub fn try_new_experimental(
locale: &DataLocale,
date_time_format_options: DateTimeFormatterOptions,
time_zone_format_options: TimeZoneFormatterOptions,
) -> Result<Self, DateTimeError> {
let calendar = AnyCalendar::new_for_locale(locale);
let kind = calendar.kind();
let patterns = PatternSelector::for_options_experimental(
&crate::provider::Baked,
calendar::load_lengths_for_any_calendar_kind(&crate::provider::Baked, locale, kind)?,
locale,
&kind.as_bcp47_value(),
&date_time_format_options,
)
.map_err(|e| match e {
UnsupportedOptionsOrDataOrPatternError::UnsupportedOptions => {
DateTimeError::UnsupportedOptions
}
UnsupportedOptionsOrDataOrPatternError::Data(e) => DateTimeError::Data(e),
UnsupportedOptionsOrDataOrPatternError::Pattern(e) => DateTimeError::Pattern(e),
})?;
Ok(Self(
raw::ZonedDateTimeFormatter::try_new(
patterns,
|| {
calendar::load_symbols_for_any_calendar_kind(
&crate::provider::Baked,
locale,
kind,
)
},
locale,
time_zone_format_options,
)?,
calendar,
))
}
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new_experimental)]
#[cfg(feature = "experimental")]
#[inline]
#[allow(clippy::too_many_arguments)]
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<crate::provider::calendar::DateSkeletonPatternsV1Marker>
+ DataProvider<WeekDataV1Marker>
+ DataProvider<provider::time_zones::TimeZoneFormatsV1Marker>
+ DataProvider<provider::time_zones::ExemplarCitiesV1Marker>
+ DataProvider<provider::time_zones::MetazoneGenericNamesLongV1Marker>
+ DataProvider<provider::time_zones::MetazoneGenericNamesShortV1Marker>
+ DataProvider<provider::time_zones::MetazoneSpecificNamesLongV1Marker>
+ DataProvider<provider::time_zones::MetazoneSpecificNamesShortV1Marker>
+ DataProvider<OrdinalV1Marker>
+ DataProvider<DecimalSymbolsV1Marker>
+ DataProvider<BuddhistDateLengthsV1Marker>
+ DataProvider<BuddhistDateSymbolsV1Marker>
+ DataProvider<ChineseCacheV1Marker>
+ DataProvider<ChineseDateLengthsV1Marker>
+ DataProvider<ChineseDateSymbolsV1Marker>
+ DataProvider<CopticDateLengthsV1Marker>
+ DataProvider<CopticDateSymbolsV1Marker>
+ DataProvider<DangiCacheV1Marker>
+ DataProvider<DangiDateLengthsV1Marker>
+ DataProvider<DangiDateSymbolsV1Marker>
+ DataProvider<EthiopianDateLengthsV1Marker>
+ DataProvider<EthiopianDateSymbolsV1Marker>
+ DataProvider<GregorianDateLengthsV1Marker>
+ DataProvider<GregorianDateSymbolsV1Marker>
+ DataProvider<HebrewDateLengthsV1Marker>
+ DataProvider<HebrewDateSymbolsV1Marker>
+ DataProvider<IndianDateLengthsV1Marker>
+ DataProvider<IndianDateSymbolsV1Marker>
+ DataProvider<IslamicDateLengthsV1Marker>
+ DataProvider<IslamicDateSymbolsV1Marker>
+ DataProvider<IslamicObservationalCacheV1Marker>
+ DataProvider<IslamicUmmAlQuraCacheV1Marker>
+ DataProvider<JapaneseDateLengthsV1Marker>
+ DataProvider<JapaneseDateSymbolsV1Marker>
+ DataProvider<JapaneseErasV1Marker>
+ DataProvider<JapaneseExtendedDateLengthsV1Marker>
+ DataProvider<JapaneseExtendedDateSymbolsV1Marker>
+ DataProvider<JapaneseExtendedErasV1Marker>
+ DataProvider<PersianDateLengthsV1Marker>
+ DataProvider<PersianDateSymbolsV1Marker>
+ DataProvider<RocDateLengthsV1Marker>
+ DataProvider<RocDateSymbolsV1Marker>
+ ?Sized,
{
let calendar = AnyCalendar::try_new_for_locale_unstable(provider, locale)?;
let kind = calendar.kind();
let patterns = PatternSelector::for_options_experimental(
provider,
calendar::load_lengths_for_any_calendar_kind(provider, locale, kind)?,
locale,
&kind.as_bcp47_value(),
&date_time_format_options,
)
.map_err(|e| match e {
UnsupportedOptionsOrDataOrPatternError::UnsupportedOptions => {
DateTimeError::UnsupportedOptions
}
UnsupportedOptionsOrDataOrPatternError::Data(e) => DateTimeError::Data(e),
UnsupportedOptionsOrDataOrPatternError::Pattern(e) => DateTimeError::Pattern(e),
})?;
Ok(Self(
raw::ZonedDateTimeFormatter::try_new_unstable(
provider,
patterns,
|| calendar::load_symbols_for_any_calendar_kind(provider, locale, kind),
locale,
time_zone_format_options,
)?,
calendar,
))
}
/// Constructor that takes a selected [`DataLocale`] and a list of [`DateTimeFormatterOptions`] and uses compiled data.
/// It collects all data necessary to format zoned datetime values into the given locale.
///
/// 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.
///
/// ✨ *Enabled with the `compiled_data` Cargo feature.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
///
/// # Examples
///
/// ```
/// use icu::calendar::DateTime;
/// use icu::datetime::options::length;
/// use icu::datetime::time_zone::TimeZoneFormatterOptions;
/// use icu::datetime::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").into();
///
/// let zdtf = ZonedDateTimeFormatter::try_new(
/// &locale,
/// 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"
/// );
/// ```
#[cfg(feature = "compiled_data")]
pub fn try_new(
locale: &DataLocale,
date_time_format_options: DateTimeFormatterOptions,
time_zone_format_options: TimeZoneFormatterOptions,
) -> Result<Self, DateTimeError> {
let calendar = AnyCalendar::new_for_locale(locale);
let kind = calendar.kind();
let patterns = PatternSelector::for_options(
&crate::provider::Baked,
calendar::load_lengths_for_any_calendar_kind(&crate::provider::Baked, locale, kind)?,
locale,
&date_time_format_options,
)
.map_err(|e| match e {
PatternForLengthError::Data(e) => DateTimeError::Data(e),
PatternForLengthError::Pattern(e) => DateTimeError::Pattern(e),
})?;
Ok(Self(
raw::ZonedDateTimeFormatter::try_new(
patterns,
|| {
calendar::load_symbols_for_any_calendar_kind(
&crate::provider::Baked,
locale,
kind,
)
},
locale,
time_zone_format_options,
)?,
calendar,
))
}
#[inline]
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
#[allow(clippy::too_many_arguments)]
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<provider::time_zones::TimeZoneFormatsV1Marker>
+ DataProvider<provider::time_zones::ExemplarCitiesV1Marker>
+ DataProvider<provider::time_zones::MetazoneGenericNamesLongV1Marker>
+ DataProvider<provider::time_zones::MetazoneGenericNamesShortV1Marker>
+ DataProvider<provider::time_zones::MetazoneSpecificNamesLongV1Marker>
+ DataProvider<provider::time_zones::MetazoneSpecificNamesShortV1Marker>
+ DataProvider<OrdinalV1Marker>
+ DataProvider<DecimalSymbolsV1Marker>
+ DataProvider<BuddhistDateLengthsV1Marker>
+ DataProvider<BuddhistDateSymbolsV1Marker>
+ DataProvider<ChineseCacheV1Marker>
+ DataProvider<ChineseDateLengthsV1Marker>
+ DataProvider<ChineseDateSymbolsV1Marker>
+ DataProvider<CopticDateLengthsV1Marker>
+ DataProvider<CopticDateSymbolsV1Marker>
+ DataProvider<DangiCacheV1Marker>
+ DataProvider<DangiDateLengthsV1Marker>
+ DataProvider<DangiDateSymbolsV1Marker>
+ DataProvider<EthiopianDateLengthsV1Marker>
+ DataProvider<EthiopianDateSymbolsV1Marker>
+ DataProvider<GregorianDateLengthsV1Marker>
+ DataProvider<GregorianDateSymbolsV1Marker>
+ DataProvider<HebrewDateLengthsV1Marker>
+ DataProvider<HebrewDateSymbolsV1Marker>
+ DataProvider<IndianDateLengthsV1Marker>
+ DataProvider<IndianDateSymbolsV1Marker>
+ DataProvider<IslamicDateLengthsV1Marker>
+ DataProvider<IslamicDateSymbolsV1Marker>
+ DataProvider<IslamicObservationalCacheV1Marker>
+ DataProvider<IslamicUmmAlQuraCacheV1Marker>
+ DataProvider<JapaneseDateLengthsV1Marker>
+ DataProvider<JapaneseDateSymbolsV1Marker>
+ DataProvider<JapaneseErasV1Marker>
+ DataProvider<JapaneseExtendedDateLengthsV1Marker>
+ DataProvider<JapaneseExtendedDateSymbolsV1Marker>
+ DataProvider<JapaneseExtendedErasV1Marker>
+ DataProvider<PersianDateLengthsV1Marker>
+ DataProvider<PersianDateSymbolsV1Marker>
+ DataProvider<RocDateLengthsV1Marker>
+ DataProvider<RocDateSymbolsV1Marker>
+ ?Sized,
{
let calendar = AnyCalendar::try_new_for_locale_unstable(provider, locale)?;
let kind = calendar.kind();
let patterns = PatternSelector::for_options(
provider,
calendar::load_lengths_for_any_calendar_kind(provider, locale, kind)?,
locale,
&date_time_format_options,
)
.map_err(|e| match e {
PatternForLengthError::Data(e) => DateTimeError::Data(e),
PatternForLengthError::Pattern(e) => DateTimeError::Pattern(e),
})?;
Ok(Self(
raw::ZonedDateTimeFormatter::try_new_unstable(
provider,
patterns,
|| calendar::load_symbols_for_any_calendar_kind(provider, locale, kind),
locale,
time_zone_format_options,
)?,
calendar,
))
}
#[doc = icu_provider::gen_any_buffer_unstable_docs!(ANY, Self::try_new)]
#[inline]
pub fn try_new_with_any_provider(
provider: &impl AnyProvider,
locale: &DataLocale,
options: DateTimeFormatterOptions,
time_zone_format_options: TimeZoneFormatterOptions,
) -> Result<Self, DateTimeError> {
let downcasting = provider.as_downcasting();
Self::try_new_unstable(&downcasting, locale, options, time_zone_format_options)
}
#[doc = icu_provider::gen_any_buffer_unstable_docs!(BUFFER, Self::try_new)]
#[inline]
#[cfg(feature = "serde")]
pub fn try_new_with_buffer_provider(
provider: &impl BufferProvider,
locale: &DataLocale,
options: DateTimeFormatterOptions,
time_zone_format_options: TimeZoneFormatterOptions,
) -> Result<Self, DateTimeError> {
let deserializing = provider.as_deserializing();
Self::try_new_unstable(&deserializing, locale, options, time_zone_format_options)
}
/// 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.
#[inline]
pub fn format<'l>(
&'l self,
date: &impl DateTimeInput<Calendar = AnyCalendar>,
time_zone: &impl TimeZoneInput,
) -> Result<FormattedZonedDateTime<'l>, DateTimeError> {
if let Some(converted) = self.convert_if_necessary(date)? {
Ok(self.0.format(&converted, time_zone))
} else {
Ok(self.0.format(date, time_zone))
}
}
/// 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.
#[inline]
pub fn format_to_string(
&self,
date: &impl DateTimeInput<Calendar = AnyCalendar>,
time_zone: &impl TimeZoneInput,
) -> Result<String, DateTimeError> {
Ok(self.format(date, time_zone)?.write_to_string().into_owned())
}
/// Converts a date to the correct calendar if necessary
///
/// Returns `Err` if the date is not ISO or compatible with the current calendar, returns `Ok(None)`
/// if the date is compatible with the current calendar and doesn't need conversion
fn convert_if_necessary(
&self,
value: &impl DateTimeInput<Calendar = AnyCalendar>,
) -> Result<Option<ExtractedDateTimeInput>, DateTimeError> {
let this_calendar = self.1.kind();
let date_calendar = value.any_calendar_kind();
if Some(this_calendar) != date_calendar {
if date_calendar != Some(AnyCalendarKind::Iso) {
return Err(DateTimeError::MismatchedAnyCalendar(
this_calendar,
date_calendar,
));
}
let date = value.to_iso();
let time = Time::new(
value.hour().unwrap_or_default(),
value.minute().unwrap_or_default(),
value.second().unwrap_or_default(),
value.nanosecond().unwrap_or_default(),
);
let datetime = DateTime::new(date, time).to_any();
let converted = self.1.convert_any_datetime(&datetime);
// FIXME(#2145) this is very hacky, can be improved after we improve ZonedDateTimeInput
let converted = ExtractedDateTimeInput::extract_from(&converted);
Ok(Some(converted))
} else {
Ok(None)
}
}
}
#[test]
#[cfg(feature = "serde")]
fn buffer_constructor() {
#![allow(clippy::zero_prefixed_literal)]
use icu::calendar::DateTime;
use icu::datetime::options::length;
use icu::datetime::ZonedDateTimeFormatter;
use icu::locid::locale;
use icu::timezone::CustomTimeZone;
use std::str::FromStr;
use writeable::assert_writeable_eq;
let provider = icu_provider_blob::BlobDataProvider::try_new_from_static_blob(include_bytes!(
"../../tests/data/blob.postcard"
))
.unwrap();
let zdtf = ZonedDateTimeFormatter::try_new_with_buffer_provider(
&provider,
&locale!("en").into(),
length::Bag::from_date_time_style(length::Date::Medium, length::Time::Long).into(),
Default::default(),
)
.unwrap();
assert_writeable_eq!(
zdtf.format(
&DateTime::try_new_iso_datetime(2021, 04, 08, 16, 12, 37)
.unwrap()
.to_any(),
&CustomTimeZone::from_str("-07:00").unwrap()
)
.unwrap(),
"Apr 8, 2021, 4:12:37 PM GMT-07:00"
);
}