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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
// 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 ).
//! The collection of code that is needed for handling formatting operations for DateTimes.
//! Central to this is the [`TypedDateTimeFormatter`].
#[cfg(feature = "experimental")]
use crate::provider::date_time::UnsupportedOptionsOrDataOrPatternError;
use crate::{
helpers::size_test,
options::{length, preferences, DateTimeFormatterOptions},
provider::{
calendar::{TimeLengthsV1Marker, TimeSymbolsV1Marker},
date_time::{PatternForLengthError, PatternSelector},
},
raw,
};
use alloc::string::String;
use core::marker::PhantomData;
use icu_calendar::provider::WeekDataV1Marker;
use icu_decimal::provider::DecimalSymbolsV1Marker;
use icu_plurals::provider::OrdinalV1Marker;
use icu_provider::prelude::*;
use writeable::Writeable;
use crate::{
calendar, calendar::CldrCalendar, input::DateInput, input::DateTimeInput, input::IsoTimeInput,
DateTimeError, FormattedDateTime,
};
size_test!(TimeFormatter, time_formatter_size, 1200);
/// [`TimeFormatter`] is a structure of the [`icu::datetime`] component that provides time formatting only.
/// When constructed, it uses data from the [data provider], selected locale and provided preferences to
/// collect all data necessary to format any time into that locale.
///
/// For that reason, one should think of the process of formatting a time in two steps - first, a computational
/// heavy construction of [`TimeFormatter`], and then fast formatting of [`DateTimeInput`] data using the instance.
#[doc = time_formatter_size!()]
///
/// [`icu::datetime`]: crate
/// [`TypedDateTimeFormatter`]: crate::datetime::TimeFormatter
///
/// # Examples
///
/// ```
/// use icu::calendar::DateTime;
/// use icu::datetime::{options::length::Time, TimeFormatter};
/// use icu::locid::locale;
/// use writeable::assert_writeable_eq;
///
/// let tf =
/// TimeFormatter::try_new_with_length(&locale!("en").into(), Time::Short)
/// .expect("Failed to create TimeFormatter instance.");
///
/// let datetime = DateTime::try_new_gregorian_datetime(2020, 9, 1, 12, 34, 28)
/// .expect("Failed to construct DateTime.");
///
/// assert_writeable_eq!(tf.format(&datetime), "12:34 PM");
/// ```
///
/// This model replicates that of `ICU` and `ECMA402`.
///
/// [data provider]: icu_provider
#[derive(Debug)]
pub struct TimeFormatter(pub(super) raw::TimeFormatter);
impl TimeFormatter {
/// Constructor that takes a selected locale and a list of preferences, then collects all
/// compiled data necessary to format date and time values into the given locale,
/// using the given style.
///
/// ✨ *Enabled with the `compiled_data` Cargo feature.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
///
/// # Examples
///
/// ```
/// use icu::datetime::{options::length::Time, TimeFormatter};
/// use icu::locid::locale;
///
/// TimeFormatter::try_new_with_length(&locale!("en").into(), Time::Short)
/// .unwrap();
/// ```
#[cfg(feature = "compiled_data")]
pub fn try_new_with_length(
locale: &DataLocale,
length: length::Time,
) -> Result<Self, DateTimeError> {
let preferences = Some(preferences::Bag::from_data_locale(locale));
Ok(Self(raw::TimeFormatter::try_new(
locale,
length,
preferences,
)?))
}
icu_provider::gen_any_buffer_data_constructors!(
locale: include,
length: length::Time,
error: DateTimeError,
#[cfg(skip)]
functions: [
try_new_with_length,
try_new_with_length_with_any_provider,
try_new_with_length_with_buffer_provider,
try_new_with_length_unstable,
Self,
]
);
#[inline]
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new_with_length)]
pub fn try_new_with_length_unstable<D>(
provider: &D,
locale: &DataLocale,
length: length::Time,
) -> Result<Self, DateTimeError>
where
D: DataProvider<TimeLengthsV1Marker>
+ DataProvider<TimeSymbolsV1Marker>
+ DataProvider<DecimalSymbolsV1Marker>
+ ?Sized,
{
let preferences = Some(preferences::Bag::from_data_locale(locale));
Ok(Self(raw::TimeFormatter::try_new_unstable(
provider,
locale,
length,
preferences,
)?))
}
/// Takes a [`IsoTimeInput`] implementer and returns an instance of a [`FormattedDateTime`]
/// that contains all information necessary to display a formatted date and operate on it.
///
/// # Examples
///
/// ```
/// use icu::calendar::DateTime;
/// use icu::datetime::{options::length::Time, TimeFormatter};
/// use icu::locid::locale;
/// use writeable::assert_writeable_eq;
///
/// let tf =
/// TimeFormatter::try_new_with_length(&locale!("en").into(), Time::Short)
/// .expect("Failed to create TimeFormatter instance.");
///
/// let datetime = DateTime::try_new_gregorian_datetime(2020, 9, 1, 12, 34, 28)
/// .expect("Failed to construct DateTime.");
///
/// assert_writeable_eq!(tf.format(&datetime), "12:34 PM");
/// ```
#[inline]
pub fn format<'l, T>(&'l self, value: &T) -> FormattedDateTime<'l>
where
T: IsoTimeInput,
{
self.0.format(value)
}
/// Takes a [`IsoTimeInput`] implementer and returns it formatted as a string.
///
/// # Examples
///
/// ```
/// use icu::calendar::DateTime;
/// use icu::datetime::{options::length::Time, TimeFormatter};
/// use icu::locid::locale;
/// let tf =
/// TimeFormatter::try_new_with_length(&locale!("en").into(), Time::Short)
/// .expect("Failed to create TimeFormatter instance.");
///
/// let datetime = DateTime::try_new_gregorian_datetime(2020, 9, 1, 12, 34, 28)
/// .expect("Failed to construct DateTime.");
///
/// assert_eq!(tf.format_to_string(&datetime), "12:34 PM");
/// ```
#[inline]
pub fn format_to_string(&self, value: &impl IsoTimeInput) -> String {
self.format(value).write_to_string().into_owned()
}
}
size_test!(
TypedDateFormatter<icu_calendar::Gregorian>,
typed_date_formatter_size,
4400
);
/// [`TypedDateFormatter`] is a formatter capable of formatting
/// dates from a calendar selected at compile time. For the difference between this
/// and [`DateFormatter`](crate::DateFormatter), please read the [crate root docs][crate].
///
/// When constructed, it uses data from the [data provider], selected locale and provided options to
/// collect all data necessary to format any dates into that locale.
///
/// For that reason, one should think of the process of formatting a date in two steps - first, a computational
/// heavy construction of [`TypedDateFormatter`], and then fast formatting of [`DateInput`] data using the instance.
#[doc = typed_date_formatter_size!()]
///
/// [`icu::datetime`]: crate
///
/// # Examples
///
/// ```
/// use icu::calendar::{Date, Gregorian};
/// use icu::datetime::{options::length, TypedDateFormatter};
/// use icu::locid::locale;
/// use writeable::assert_writeable_eq;
///
/// let df = TypedDateFormatter::<Gregorian>::try_new_with_length(
/// &locale!("en").into(),
/// length::Date::Full,
/// )
/// .expect("Failed to create TypedDateFormatter instance.");
///
/// let date = Date::try_new_gregorian_date(2020, 9, 1)
/// .expect("Failed to construct Date.");
///
/// assert_writeable_eq!(df.format(&date), "Tuesday, September 1, 2020");
/// ```
///
/// This model replicates that of `ICU` and `ECMA402`.
///
/// [data provider]: icu_provider
#[derive(Debug)]
pub struct TypedDateFormatter<C>(pub(super) raw::DateFormatter, PhantomData<C>);
impl<C: CldrCalendar> TypedDateFormatter<C> {
/// Constructor that takes a selected locale and a list of options, then collects all
/// compiled data necessary to format date and time values into the given locale.
///
/// ✨ *Enabled with the `compiled_data` Cargo feature.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
///
/// # Examples
///
/// ```
/// use icu::calendar::Date;
/// use icu::calendar::Gregorian;
/// use icu::datetime::{options::length, TypedDateFormatter};
/// use icu::locid::locale;
/// use writeable::assert_writeable_eq;
///
/// let formatter = TypedDateFormatter::<Gregorian>::try_new_with_length(
/// &locale!("en").into(),
/// length::Date::Full,
/// )
/// .unwrap();
///
/// assert_writeable_eq!(
/// formatter.format(&Date::try_new_gregorian_date(2022, 8, 29).unwrap()),
/// "Monday, August 29, 2022",
/// );
/// ```
///
/// If the locale has a calendar keyword, the keyword is ignored in favor of the
/// type parameter on the [`TypedDateFormatter`]. To obey the calendar keyword,
/// use [`DateFormatter`] instead.
///
/// ```
/// use icu::calendar::indian::Indian;
/// use icu::calendar::Date;
/// use icu::datetime::{options::length, TypedDateFormatter};
/// use icu::locid::locale;
/// use writeable::assert_writeable_eq;
///
/// let formatter = TypedDateFormatter::<Indian>::try_new_with_length(
/// &locale!("en-u-ca-japanese").into(),
/// length::Date::Full,
/// )
/// .unwrap();
///
/// // Indian format from type wins over locale keyword
/// assert_writeable_eq!(
/// formatter.format(&Date::try_new_indian_date(1944, 6, 7).unwrap()),
/// "Monday, Bhadra 7, 1944 Saka",
/// );
/// ```
///
/// [`DateFormatter`]: crate::DateFormatter
#[cfg(feature = "compiled_data")]
pub fn try_new_with_length(
locale: &DataLocale,
length: length::Date,
) -> Result<Self, DateTimeError>
where
crate::provider::Baked: icu_provider::DataProvider<<C as CldrCalendar>::DateLengthsV1Marker>
+ icu_provider::DataProvider<<C as CldrCalendar>::DateSymbolsV1Marker>,
{
Ok(Self(
raw::DateFormatter::try_new(
calendar::load_lengths_for_cldr_calendar::<C, _>(&crate::provider::Baked, locale)?,
|| {
calendar::load_symbols_for_cldr_calendar::<C, _>(
&crate::provider::Baked,
locale,
)
},
locale,
length,
)?,
PhantomData,
))
}
icu_provider::gen_any_buffer_data_constructors!(
locale: include,
length: length::Date,
error: DateTimeError,
#[cfg(skip)]
functions: [
try_new_with_length,
try_new_with_length_with_any_provider,
try_new_with_length_with_buffer_provider,
try_new_with_length_unstable,
Self,
]
);
#[inline]
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new_with_length)]
pub fn try_new_with_length_unstable<D>(
provider: &D,
locale: &DataLocale,
length: length::Date,
) -> Result<Self, DateTimeError>
where
D: DataProvider<<C as CldrCalendar>::DateSymbolsV1Marker>
+ DataProvider<<C as CldrCalendar>::DateLengthsV1Marker>
+ DataProvider<DecimalSymbolsV1Marker>
+ DataProvider<OrdinalV1Marker>
+ DataProvider<WeekDataV1Marker>
+ ?Sized,
{
Ok(Self(
raw::DateFormatter::try_new_unstable(
provider,
calendar::load_lengths_for_cldr_calendar::<C, _>(provider, locale)?,
|| calendar::load_symbols_for_cldr_calendar::<C, _>(provider, locale),
locale,
length,
)?,
PhantomData,
))
}
/// Takes a [`DateTimeInput`] implementer and returns an instance of a [`FormattedDateTime`]
/// that contains all information necessary to display a formatted date and operate on it.
///
/// # Examples
///
/// ```
/// use icu::calendar::{Date, Gregorian};
/// use icu::datetime::{options::length, TypedDateFormatter};
/// use icu::locid::locale;
/// use writeable::assert_writeable_eq;
/// let df = TypedDateFormatter::<Gregorian>::try_new_with_length(
/// &locale!("en").into(),
/// length::Date::Full,
/// )
/// .expect("Failed to create TypedDateFormatter instance.");
///
/// let date = Date::try_new_gregorian_date(2020, 9, 1)
/// .expect("Failed to construct Date.");
///
/// assert_writeable_eq!(df.format(&date), "Tuesday, September 1, 2020");
/// ```
#[inline]
pub fn format<'l, T>(&'l self, value: &T) -> FormattedDateTime<'l>
where
T: DateInput<Calendar = C>,
{
self.0.format(value)
}
/// Takes a [`DateTimeInput`] implementer and returns it formatted as a string.
///
/// # Examples
///
/// ```
/// use icu::calendar::{Date, Gregorian};
/// use icu::datetime::{options::length, TypedDateFormatter};
/// use icu::locid::locale;
/// let df = TypedDateFormatter::<Gregorian>::try_new_with_length(
/// &locale!("en").into(),
/// length::Date::Short,
/// )
/// .expect("Failed to create TypedDateTimeFormatter instance.");
///
/// let date = Date::try_new_gregorian_date(2020, 9, 1)
/// .expect("Failed to construct Date.");
///
/// assert_eq!(df.format_to_string(&date), "9/1/20");
/// ```
#[inline]
pub fn format_to_string(&self, value: &impl DateInput<Calendar = C>) -> String {
self.format(value).write_to_string().into_owned()
}
}
size_test!(
TypedDateTimeFormatter<icu_calendar::Gregorian>,
typed_date_time_formatter_size,
5152
);
/// [`TypedDateTimeFormatter`] is a formatter capable of formatting
/// date/times from a calendar selected at compile time. For the difference between this
/// and [`DateTimeFormatter`](crate::DateTimeFormatter), please read the [crate root docs][crate].
///
/// When constructed, it uses data from the [data provider], selected locale and provided options to
/// collect all data necessary to format any dates into that locale.
///
/// For that reason, one should think of the process of formatting a date in two steps - first, a computational
/// heavy construction of [`TypedDateTimeFormatter`], and then fast formatting of [`DateInput`] data using the instance.
#[doc = typed_date_time_formatter_size!()]
///
/// [`icu::datetime`]: crate
/// [`TypedDateTimeFormatter`]: crate::datetime::TypedDateTimeFormatter
///
/// # Examples
///
/// ```
/// use icu::calendar::{DateTime, Gregorian};
/// use icu::datetime::{options::length, TypedDateTimeFormatter};
/// use icu::locid::locale;
/// use writeable::assert_writeable_eq;
///
/// let mut options = length::Bag::from_date_time_style(
/// length::Date::Medium,
/// length::Time::Short,
/// );
///
/// let dtf = TypedDateTimeFormatter::<Gregorian>::try_new(
/// &locale!("en").into(),
/// options.into(),
/// )
/// .expect("Failed to create TypedDateTimeFormatter instance.");
///
/// let datetime = DateTime::try_new_gregorian_datetime(2020, 9, 1, 12, 34, 28)
/// .expect("Failed to construct DateTime.");
///
/// assert_writeable_eq!(dtf.format(&datetime), "Sep 1, 2020, 12:34 PM");
/// ```
///
/// This model replicates that of `ICU` and `ECMA402`.
///
/// [data provider]: icu_provider
#[derive(Debug)]
pub struct TypedDateTimeFormatter<C>(pub(super) raw::DateTimeFormatter, PhantomData<C>);
impl<C: CldrCalendar> TypedDateTimeFormatter<C> {
/// Constructor that takes a [`TimeFormatter`] and [`TypedDateFormatter`] and combines them into a [`TypedDateTimeFormatter`].
///
/// # Examples
///
/// ```
/// use icu::calendar::Gregorian;
/// use icu::datetime::{
/// options::length, TimeFormatter, TypedDateFormatter,
/// TypedDateTimeFormatter,
/// };
/// use icu::locid::locale;
///
/// let tf = TimeFormatter::try_new_with_length(
/// &locale!("en").into(),
/// length::Time::Short,
/// )
/// .expect("Failed to create TimeFormatter instance.");
/// let df = TypedDateFormatter::<Gregorian>::try_new_with_length(
/// &locale!("en").into(),
/// length::Date::Short,
/// )
/// .expect("Failed to create TypedDateFormatter instance.");
///
/// TypedDateTimeFormatter::<Gregorian>::try_from_date_and_time(df, tf)
/// .unwrap();
/// ```
///
/// [data provider]: icu_provider
#[inline]
pub fn try_from_date_and_time(
date: TypedDateFormatter<C>,
time: TimeFormatter,
) -> Result<Self, DateTimeError>
where {
Ok(Self(
raw::DateTimeFormatter::try_from_date_and_time(date.0, time.0)?,
PhantomData,
))
}
/// Constructor that takes a selected locale, then collects all
/// compiled data necessary to format date and time values into the given locale.
///
/// ✨ *Enabled with the `compiled_data` Cargo feature.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
///
/// # Examples
///
/// ```
/// use icu::calendar::{DateTime, Gregorian};
/// use icu::datetime::{options::length, TypedDateTimeFormatter};
/// use icu::locid::locale;
/// use writeable::assert_writeable_eq;
///
/// let options = length::Bag::from_date_time_style(
/// length::Date::Medium,
/// length::Time::Medium,
/// );
///
/// let dtf = TypedDateTimeFormatter::<Gregorian>::try_new(
/// &locale!("en").into(),
/// options.into(),
/// )
/// .unwrap();
///
/// let datetime =
/// DateTime::try_new_gregorian_datetime(2022, 8, 31, 1, 2, 3).unwrap();
///
/// assert_writeable_eq!(dtf.format(&datetime), "Aug 31, 2022, 1:02:03 AM");
/// ```
///
/// [data provider]: icu_provider
#[cfg(feature = "compiled_data")]
pub fn try_new(
locale: &DataLocale,
options: DateTimeFormatterOptions,
) -> Result<Self, DateTimeError>
where
crate::provider::Baked: DataProvider<<C as CldrCalendar>::DateLengthsV1Marker>,
crate::provider::Baked: DataProvider<<C as CldrCalendar>::DateSymbolsV1Marker>,
{
let patterns = PatternSelector::for_options(
&crate::provider::Baked,
calendar::load_lengths_for_cldr_calendar::<C, _>(&crate::provider::Baked, locale)?,
locale,
&options,
)
.map_err(|e| match e {
PatternForLengthError::Data(e) => DateTimeError::Data(e),
PatternForLengthError::Pattern(e) => DateTimeError::Pattern(e),
})?;
Ok(Self(
raw::DateTimeFormatter::try_new(
patterns,
|| {
calendar::load_symbols_for_cldr_calendar::<C, _>(
&crate::provider::Baked,
locale,
)
},
locale,
)?,
PhantomData,
))
}
icu_provider::gen_any_buffer_data_constructors!(
locale: include,
options: DateTimeFormatterOptions,
error: DateTimeError,
#[cfg(skip)]
functions: [
try_new,
try_new_with_any_provider,
try_new_with_buffer_provider,
try_new_unstable,
Self
]
);
#[inline]
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
pub fn try_new_unstable<D>(
provider: &D,
locale: &DataLocale,
options: DateTimeFormatterOptions,
) -> Result<Self, DateTimeError>
where
D: DataProvider<<C as CldrCalendar>::DateSymbolsV1Marker>
+ DataProvider<<C as CldrCalendar>::DateLengthsV1Marker>
+ DataProvider<TimeSymbolsV1Marker>
+ DataProvider<TimeLengthsV1Marker>
+ DataProvider<DecimalSymbolsV1Marker>
+ DataProvider<OrdinalV1Marker>
+ DataProvider<WeekDataV1Marker>
+ ?Sized,
{
let patterns = PatternSelector::for_options(
provider,
calendar::load_lengths_for_cldr_calendar::<C, _>(provider, locale)?,
locale,
&options,
)
.map_err(|e| match e {
PatternForLengthError::Data(e) => DateTimeError::Data(e),
PatternForLengthError::Pattern(e) => DateTimeError::Pattern(e),
})?;
Ok(Self(
raw::DateTimeFormatter::try_new_unstable(
provider,
patterns,
|| calendar::load_symbols_for_cldr_calendar::<C, _>(provider, locale),
locale,
)?,
PhantomData,
))
}
/// Constructor that supports experimental options using compiled data.
///
/// ✨ *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, Gregorian};
/// use icu::datetime::{options::components, TypedDateTimeFormatter};
/// use icu::locid::locale;
/// use writeable::assert_writeable_eq;
///
/// let mut options = components::Bag::default();
/// options.year = Some(components::Year::Numeric);
/// options.month = Some(components::Month::Long);
///
/// let dtf = TypedDateTimeFormatter::<Gregorian>::try_new_experimental(
/// &locale!("en").into(),
/// options.into(),
/// )
/// .unwrap();
///
/// let datetime =
/// DateTime::try_new_gregorian_datetime(2022, 8, 31, 1, 2, 3).unwrap();
///
/// assert_writeable_eq!(dtf.format(&datetime), "August 2022");
/// ```
///
/// [data provider]: icu_provider
#[cfg(feature = "experimental")]
#[inline]
#[cfg(feature = "compiled_data")]
pub fn try_new_experimental(
locale: &DataLocale,
options: DateTimeFormatterOptions,
) -> Result<Self, DateTimeError>
where
crate::provider::Baked: DataProvider<<C as CldrCalendar>::DateLengthsV1Marker>,
crate::provider::Baked: DataProvider<<C as CldrCalendar>::DateSymbolsV1Marker>,
{
let patterns = PatternSelector::for_options_experimental(
&crate::provider::Baked,
calendar::load_lengths_for_cldr_calendar::<C, _>(&crate::provider::Baked, locale)?,
locale,
&C::DEFAULT_BCP_47_IDENTIFIER,
&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::DateTimeFormatter::try_new(
patterns,
|| {
calendar::load_symbols_for_cldr_calendar::<C, _>(
&crate::provider::Baked,
locale,
)
},
locale,
)?,
PhantomData,
))
}
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new_experimental)]
#[cfg(feature = "experimental")]
#[inline]
pub fn try_new_experimental_unstable<D>(
provider: &D,
locale: &DataLocale,
options: DateTimeFormatterOptions,
) -> Result<Self, DateTimeError>
where
D: DataProvider<<C as CldrCalendar>::DateSymbolsV1Marker>
+ DataProvider<<C as CldrCalendar>::DateLengthsV1Marker>
+ DataProvider<TimeSymbolsV1Marker>
+ DataProvider<TimeLengthsV1Marker>
+ DataProvider<crate::provider::calendar::DateSkeletonPatternsV1Marker>
+ DataProvider<DecimalSymbolsV1Marker>
+ DataProvider<OrdinalV1Marker>
+ DataProvider<WeekDataV1Marker>
+ ?Sized,
{
let patterns = PatternSelector::for_options_experimental(
provider,
calendar::load_lengths_for_cldr_calendar::<C, _>(provider, locale)?,
locale,
&C::DEFAULT_BCP_47_IDENTIFIER,
&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::DateTimeFormatter::try_new_unstable(
provider,
patterns,
|| calendar::load_symbols_for_cldr_calendar::<C, _>(provider, locale),
locale,
)?,
PhantomData,
))
}
/// Takes a [`DateTimeInput`] implementer and returns an instance of a [`FormattedDateTime`]
/// that contains all information necessary to display a formatted date and operate on it.
///
/// # Examples
///
/// ```
/// use icu::calendar::{DateTime, Gregorian};
/// use icu::datetime::TypedDateTimeFormatter;
/// use writeable::assert_writeable_eq;
/// use icu::locid::locale;
/// # let options = icu::datetime::options::length::Bag::from_time_style(icu::datetime::options::length::Time::Medium);
/// let dtf = TypedDateTimeFormatter::<Gregorian>::try_new(&locale!("en").into(), options.into())
/// .expect("Failed to create TypedDateTimeFormatter instance.");
///
/// let datetime = DateTime::try_new_gregorian_datetime(2020, 9, 1, 12, 34, 28)
/// .expect("Failed to construct DateTime.");
///
/// assert_writeable_eq!(dtf.format(&datetime), "12:34:28 PM");
/// ```
#[inline]
pub fn format<'l, T>(&'l self, value: &T) -> FormattedDateTime<'l>
where
T: DateTimeInput<Calendar = C>,
{
self.0.format(value)
}
/// Takes a [`DateTimeInput`] implementer and returns it formatted as a string.
///
/// # Examples
///
/// ```
/// use icu::calendar::{DateTime, Gregorian};
/// use icu::datetime::TypedDateTimeFormatter;
/// use icu::locid::locale;
/// # let options = icu::datetime::options::length::Bag::from_time_style(icu::datetime::options::length::Time::Medium);
/// let dtf = TypedDateTimeFormatter::<Gregorian>::try_new(&locale!("en").into(), options.into())
/// .expect("Failed to create TypedDateTimeFormatter instance.");
///
/// let datetime = DateTime::try_new_gregorian_datetime(2020, 9, 1, 12, 34, 28)
/// .expect("Failed to construct DateTime.");
///
/// assert_eq!(dtf.format_to_string(&datetime), "12:34:28 PM");
/// ```
#[inline]
pub fn format_to_string(&self, value: &impl DateTimeInput<Calendar = C>) -> String {
self.format(value).write_to_string().into_owned()
}
/// Returns a [`components::Bag`](crate::options::components::Bag) that represents the resolved components for the
/// options that were provided to the [`TypedDateTimeFormatter`]. The developer may request
/// a certain set of options for a [`TypedDateTimeFormatter`] but the locale and resolution
/// algorithm may change certain details of what actually gets resolved.
///
/// # Examples
///
/// ```
/// use icu::calendar::Gregorian;
/// use icu::datetime::{
/// options::{components, length},
/// TypedDateTimeFormatter,
/// };
/// use icu::locid::locale;
///
/// let options = length::Bag::from_date_style(length::Date::Medium).into();
/// let dtf = TypedDateTimeFormatter::<Gregorian>::try_new(
/// &locale!("en").into(),
/// options,
/// )
/// .expect("Failed to create TypedDateTimeFormatter instance.");
///
/// let mut expected_components_bag = components::Bag::default();
/// expected_components_bag.year = Some(components::Year::Numeric);
/// expected_components_bag.month = Some(components::Month::Short);
/// expected_components_bag.day = Some(components::Day::NumericDayOfMonth);
///
/// assert_eq!(dtf.resolve_components(), expected_components_bag);
/// ```
#[cfg(feature = "experimental")]
pub fn resolve_components(&self) -> crate::options::components::Bag {
self.0.resolve_components()
}
}
#[cfg(test)]
#[cfg(feature = "serde")]
#[cfg(feature = "compiled_data")]
mod tests {
use super::*;
use icu_calendar::DateTime;
use icu_calendar::Gregorian;
#[test]
fn works_with_default_options() {
assert_eq!(
TypedDateTimeFormatter::<Gregorian>::try_new(Default::default(), Default::default(),)
.unwrap()
.format_to_string(
&DateTime::try_new_gregorian_datetime(2022, 9, 20, 0, 0, 0).unwrap()
),
"2022 M09 20 00:00:00"
);
}
}