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 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
// 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 ).
//! High-level entrypoints for Neo DateTime Formatter
use crate::error::DateTimeFormatterLoadError;
use crate::external_loaders::*;
use crate::fieldsets::enums::CompositeFieldSet;
use crate::format::datetime::try_write_pattern_items;
use crate::input::ExtractedInput;
use crate::pattern::*;
use crate::raw::neo::*;
use crate::scaffold::*;
use crate::scaffold::{
AllInputMarkers, ConvertCalendar, DateDataMarkers, DateInputMarkers, DateTimeMarkers, GetField,
InFixedCalendar, InSameCalendar, TimeMarkers, TypedDateDataMarkers, ZoneMarkers,
};
use crate::size_test_macro::size_test;
use crate::MismatchedCalendarError;
use core::fmt;
use core::marker::PhantomData;
use icu_calendar::any_calendar::IntoAnyCalendar;
use icu_calendar::{AnyCalendar, AnyCalendarKind, AnyCalendarPreferences};
use icu_decimal::FixedDecimalFormatterPreferences;
use icu_locale_core::preferences::extensions::unicode::keywords::{
CalendarAlgorithm, HourCycle, NumberingSystem,
};
use icu_locale_core::preferences::{define_preferences, prefs_convert};
use icu_provider::prelude::*;
use writeable::{impl_display_with_writeable, Writeable};
define_preferences!(
/// The user locale preferences for datetime formatting.
///
/// # Examples
///
/// Two ways to build a preferences bag with a custom hour cycle and calendar system:
///
/// ```
/// use icu::datetime::DateTimeFormatterPreferences;
/// use icu::locale::Locale;
/// use icu::locale::preferences::extensions::unicode::keywords::CalendarAlgorithm;
/// use icu::locale::preferences::extensions::unicode::keywords::HourCycle;
/// use icu::locale::subtags::Language;
///
/// let prefs1: DateTimeFormatterPreferences = Locale::try_from_str("fr-u-ca-buddhist-hc-h12").unwrap().into();
///
/// let mut prefs2 = DateTimeFormatterPreferences::default();
/// prefs2.locale_prefs.language = Language::try_from_str("fr").unwrap();
/// prefs2.hour_cycle = Some(HourCycle::H12);
/// prefs2.calendar_algorithm = Some(CalendarAlgorithm::Buddhist);
///
/// assert_eq!(prefs1, prefs2);
/// ```
[Copy]
DateTimeFormatterPreferences,
{
/// The user's preferred numbering system.
///
/// Corresponds to the `-u-nu` in Unicode Locale Identifier.
///
/// To get the resolved numbering system, you can inspect the data provider.
/// See the [`icu_decimal::provider`] module for an example.
numbering_system: NumberingSystem,
/// The user's preferred hour cycle.
///
/// Corresponds to the `-u-hc` in Unicode Locale Identifier.
///
/// To get the resolved hour cycle, you can inspect the formatting pattern.
/// See [`DateTimePattern`](crate::pattern::DateTimePattern) for an example.
hour_cycle: HourCycle,
/// The user's preferred calendar system
///
/// Corresponds to the `-u-ca` in Unicode Locale Identifier.
///
/// To get the resolved calendar system, use [`DateTimeFormatter::calendar_kind()`].
calendar_algorithm: CalendarAlgorithm
}
);
prefs_convert!(
DateTimeFormatterPreferences,
FixedDecimalFormatterPreferences,
{ numbering_system }
);
prefs_convert!(DateTimeFormatterPreferences, AnyCalendarPreferences, {
calendar_algorithm
});
/// Helper macro for generating any/buffer constructors in this file.
macro_rules! gen_any_buffer_constructors_with_external_loader {
(@runtime_fset, $fset:ident, $compiled_fn:ident, $any_fn:ident, $buffer_fn:ident, $internal_fn:ident) => {
#[doc = icu_provider::gen_any_buffer_unstable_docs!(ANY, Self::$compiled_fn)]
pub fn $any_fn<P>(
provider: &P,
prefs: DateTimeFormatterPreferences,
field_set: $fset,
) -> Result<Self, DateTimeFormatterLoadError>
where
P: AnyProvider + ?Sized,
{
Self::$internal_fn(
&provider.as_downcasting(),
&ExternalLoaderAny(provider),
prefs,
field_set.get_field(),
)
}
#[doc = icu_provider::gen_any_buffer_unstable_docs!(BUFFER, Self::$compiled_fn)]
#[cfg(feature = "serde")]
pub fn $buffer_fn<P>(
provider: &P,
prefs: DateTimeFormatterPreferences,
field_set: $fset,
) -> Result<Self, DateTimeFormatterLoadError>
where
P: BufferProvider + ?Sized,
{
Self::$internal_fn(
&provider.as_deserializing(),
&ExternalLoaderBuffer(provider),
prefs,
field_set.get_field(),
)
}
};
(@compiletime_fset, $fset:ident, $compiled_fn:ident, $any_fn:ident, $buffer_fn:ident, $internal_fn:ident) => {
#[doc = icu_provider::gen_any_buffer_unstable_docs!(ANY, Self::$compiled_fn)]
pub fn $any_fn<P>(
provider: &P,
prefs: DateTimeFormatterPreferences,
field_set: $fset,
) -> Result<Self, DateTimeFormatterLoadError>
where
P: AnyProvider + ?Sized,
{
Self::$internal_fn(
&provider.as_downcasting(),
&ExternalLoaderAny(provider),
prefs,
field_set.get_field(),
)
}
#[doc = icu_provider::gen_any_buffer_unstable_docs!(BUFFER, Self::$compiled_fn)]
#[cfg(feature = "serde")]
pub fn $buffer_fn<P>(
provider: &P,
prefs: DateTimeFormatterPreferences,
field_set: $fset,
) -> Result<Self, DateTimeFormatterLoadError>
where
P: BufferProvider + ?Sized,
{
Self::$internal_fn(
&provider.as_deserializing(),
&ExternalLoaderBuffer(provider),
prefs,
field_set.get_field(),
)
}
};
}
size_test!(FixedCalendarDateTimeFormatter<icu_calendar::Gregorian, crate::fieldsets::YMD>, typed_neo_year_month_day_formatter_size, 344);
/// [`FixedCalendarDateTimeFormatter`] is a formatter capable of formatting dates and/or times from
/// a calendar selected at compile time.
///
/// For more details, please read the [crate root docs][crate].
#[doc = typed_neo_year_month_day_formatter_size!()]
#[derive(Debug)]
pub struct FixedCalendarDateTimeFormatter<C: CldrCalendar, FSet: DateTimeNamesMarker> {
selection: DateTimeZonePatternSelectionData,
names: RawDateTimeNames<FSet>,
_calendar: PhantomData<C>,
}
impl<C: CldrCalendar, FSet: DateTimeMarkers> FixedCalendarDateTimeFormatter<C, FSet>
where
FSet::D: TypedDateDataMarkers<C>,
FSet::T: TimeMarkers,
FSet::Z: ZoneMarkers,
FSet: GetField<CompositeFieldSet>,
{
/// Creates a new [`FixedCalendarDateTimeFormatter`] from compiled data with
/// datetime components specified at build time.
///
/// 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.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use icu::calendar::Date;
/// use icu::calendar::Gregorian;
/// use icu::datetime::fieldsets::YMD;
/// use icu::datetime::FixedCalendarDateTimeFormatter;
/// use icu::locale::locale;
/// use writeable::assert_writeable_eq;
///
/// let formatter = FixedCalendarDateTimeFormatter::try_new(
/// locale!("es-MX").into(),
/// YMD::long(),
/// )
/// .unwrap();
///
/// assert_writeable_eq!(
/// formatter.format(&Date::try_new_gregorian(2023, 12, 20).unwrap()),
/// "20 de diciembre de 2023"
/// );
/// ```
#[cfg(feature = "compiled_data")]
pub fn try_new(
prefs: DateTimeFormatterPreferences,
field_set: FSet,
) -> Result<Self, DateTimeFormatterLoadError>
where
crate::provider::Baked: AllFixedCalendarFormattingDataMarkers<C, FSet>,
{
Self::try_new_internal(
&crate::provider::Baked,
&ExternalLoaderCompiledData,
prefs,
field_set.get_field(),
)
}
gen_any_buffer_constructors_with_external_loader!(
@compiletime_fset,
FSet,
try_new,
try_new_with_any_provider,
try_new_with_buffer_provider,
try_new_internal
);
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
pub fn try_new_unstable<P>(
provider: &P,
prefs: DateTimeFormatterPreferences,
field_set: FSet,
) -> Result<Self, DateTimeFormatterLoadError>
where
P: ?Sized
+ AllFixedCalendarFormattingDataMarkers<C, FSet>
+ AllFixedCalendarExternalDataMarkers,
{
Self::try_new_internal(
provider,
&ExternalLoaderUnstable(provider),
prefs,
field_set.get_field(),
)
}
}
impl<C: CldrCalendar, FSet: DateTimeMarkers> FixedCalendarDateTimeFormatter<C, FSet>
where
FSet::D: TypedDateDataMarkers<C>,
FSet::T: TimeMarkers,
FSet::Z: ZoneMarkers,
{
fn try_new_internal<P, L>(
provider: &P,
loader: &L,
prefs: DateTimeFormatterPreferences,
field_set: CompositeFieldSet,
) -> Result<Self, DateTimeFormatterLoadError>
where
P: ?Sized + AllFixedCalendarFormattingDataMarkers<C, FSet>,
L: FixedDecimalFormatterLoader,
{
let selection = DateTimeZonePatternSelectionData::try_new_with_skeleton(
&<FSet::D as TypedDateDataMarkers<C>>::DateSkeletonPatternsV1Marker::bind(provider),
&<FSet::T as TimeMarkers>::TimeSkeletonPatternsV1Marker::bind(provider),
&FSet::GluePatternV1Marker::bind(provider),
prefs,
field_set,
)
.map_err(DateTimeFormatterLoadError::Data)?;
let mut names = RawDateTimeNames::new_without_number_formatting();
names
.load_for_pattern(
&<FSet::D as TypedDateDataMarkers<C>>::YearNamesV1Marker::bind(provider),
&<FSet::D as TypedDateDataMarkers<C>>::MonthNamesV1Marker::bind(provider),
&<FSet::D as TypedDateDataMarkers<C>>::WeekdayNamesV1Marker::bind(provider),
&<FSet::T as TimeMarkers>::DayPeriodNamesV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::EssentialsV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::LocationsV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::GenericLongV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::GenericShortV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::SpecificLongV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::SpecificShortV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::MetazonePeriodV1Marker::bind(provider),
loader, // fixed decimal formatter
prefs,
selection.pattern_items_for_data_loading(),
)
.map_err(DateTimeFormatterLoadError::Names)?;
Ok(Self {
selection,
names,
_calendar: PhantomData,
})
}
}
impl<C: CldrCalendar, FSet: DateTimeMarkers> FixedCalendarDateTimeFormatter<C, FSet>
where
FSet::D: DateInputMarkers,
FSet::T: TimeMarkers,
FSet::Z: ZoneMarkers,
{
/// Formats a datetime. Calendars and fields must match at compile time.
///
/// # Examples
///
/// Mismatched calendars will not compile:
///
/// ```compile_fail
/// use icu::calendar::Date;
/// use icu::calendar::cal::Buddhist;
/// use icu::datetime::FixedCalendarDateTimeFormatter;
/// use icu::datetime::fieldsets::YMD;
/// use icu::locale::locale;
///
/// let formatter =
/// FixedCalendarDateTimeFormatter::<Buddhist, _>::try_new(
/// locale!("es-MX").into(),
/// YMD::long(),
/// )
/// .unwrap();
///
/// // type mismatch resolving `<Gregorian as AsCalendar>::Calendar == Buddhist`
/// formatter.format(&Date::try_new_gregorian(2023, 12, 20).unwrap());
/// ```
///
/// A time cannot be passed into the formatter when a date is expected:
///
/// ```compile_fail
/// use icu::calendar::Time;
/// use icu::calendar::Gregorian;
/// use icu::datetime::FixedCalendarDateTimeFormatter;
/// use icu::datetime::fieldsets::YMD;
/// use icu::locale::locale;
///
/// let formatter =
/// FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
/// locale!("es-MX").into(),
/// YMD::long(),
/// )
/// .unwrap();
///
/// // the trait `GetField<AnyCalendarKind>`
/// // is not implemented for `icu::icu_calendar::Time`
/// formatter.format(&Time::try_new(0, 0, 0, 0).unwrap());
/// ```
pub fn format<I>(&self, input: &I) -> FormattedDateTime
where
I: ?Sized + InFixedCalendar<C> + AllInputMarkers<FSet>,
{
let input = ExtractedInput::extract_from_neo_input::<FSet::D, FSet::T, FSet::Z, I>(input);
FormattedDateTime {
pattern: self.selection.select(&input),
input,
names: self.names.as_borrowed(),
}
}
}
size_test!(
DateTimeFormatter<crate::fieldsets::YMD>,
neo_year_month_day_formatter_size,
400
);
/// [`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][crate].
#[doc = neo_year_month_day_formatter_size!()]
#[derive(Debug)]
pub struct DateTimeFormatter<FSet: DateTimeNamesMarker> {
selection: DateTimeZonePatternSelectionData,
names: RawDateTimeNames<FSet>,
calendar: AnyCalendar,
}
impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet>
where
FSet::D: DateDataMarkers,
FSet::T: TimeMarkers,
FSet::Z: ZoneMarkers,
FSet: GetField<CompositeFieldSet>,
{
/// 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](icu_provider::constructors)
///
/// # 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"
/// );
/// ```
///
/// [`AnyCalendarKind`]: icu_calendar::AnyCalendarKind
#[inline(never)]
#[cfg(feature = "compiled_data")]
pub fn try_new(
prefs: DateTimeFormatterPreferences,
field_set: FSet,
) -> Result<Self, DateTimeFormatterLoadError>
where
crate::provider::Baked: AllAnyCalendarFormattingDataMarkers<FSet>,
{
Self::try_new_internal(
&crate::provider::Baked,
&ExternalLoaderCompiledData,
prefs,
field_set.get_field(),
)
}
gen_any_buffer_constructors_with_external_loader!(
@compiletime_fset,
FSet,
try_new,
try_new_with_any_provider,
try_new_with_buffer_provider,
try_new_internal
);
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
pub fn try_new_unstable<P>(
provider: &P,
prefs: DateTimeFormatterPreferences,
field_set: FSet,
) -> Result<Self, DateTimeFormatterLoadError>
where
P: ?Sized + AllAnyCalendarFormattingDataMarkers<FSet> + AllAnyCalendarExternalDataMarkers,
{
Self::try_new_internal(
provider,
&ExternalLoaderUnstable(provider),
prefs,
field_set.get_field(),
)
}
}
impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet>
where
FSet::D: DateDataMarkers,
FSet::T: TimeMarkers,
FSet::Z: ZoneMarkers,
{
fn try_new_internal<P, L>(
provider: &P,
loader: &L,
prefs: DateTimeFormatterPreferences,
field_set: CompositeFieldSet,
) -> Result<Self, DateTimeFormatterLoadError>
where
P: ?Sized + AllAnyCalendarFormattingDataMarkers<FSet>,
L: FixedDecimalFormatterLoader + AnyCalendarLoader,
{
let calendar = AnyCalendarLoader::load(loader, (&prefs).into())
.map_err(DateTimeFormatterLoadError::Data)?;
let kind = calendar.kind();
let selection = DateTimeZonePatternSelectionData::try_new_with_skeleton(
&AnyCalendarProvider::<<FSet::D as DateDataMarkers>::Skel, _>::new(provider, kind),
&<FSet::T as TimeMarkers>::TimeSkeletonPatternsV1Marker::bind(provider),
&FSet::GluePatternV1Marker::bind(provider),
prefs,
field_set,
)
.map_err(DateTimeFormatterLoadError::Data)?;
let mut names = RawDateTimeNames::new_without_number_formatting();
names
.load_for_pattern(
&AnyCalendarProvider::<<FSet::D as DateDataMarkers>::Year, _>::new(provider, kind),
&AnyCalendarProvider::<<FSet::D as DateDataMarkers>::Month, _>::new(provider, kind),
&<FSet::D as DateDataMarkers>::WeekdayNamesV1Marker::bind(provider),
&<FSet::T as TimeMarkers>::DayPeriodNamesV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::EssentialsV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::LocationsV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::GenericLongV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::GenericShortV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::SpecificLongV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::SpecificShortV1Marker::bind(provider),
&<FSet::Z as ZoneMarkers>::MetazonePeriodV1Marker::bind(provider),
loader, // fixed decimal formatter
prefs,
selection.pattern_items_for_data_loading(),
)
.map_err(DateTimeFormatterLoadError::Names)?;
Ok(Self {
selection,
names,
calendar,
})
}
}
impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet>
where
FSet::D: DateInputMarkers,
FSet::T: TimeMarkers,
FSet::Z: ZoneMarkers,
{
/// 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:
///
/// ```compile_fail
/// 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());
/// ```
pub fn format_same_calendar<I>(
&self,
datetime: &I,
) -> Result<FormattedDateTime, crate::MismatchedCalendarError>
where
I: ?Sized + InSameCalendar + AllInputMarkers<FSet>,
{
datetime.check_any_calendar_kind(self.calendar.kind())?;
let datetime =
ExtractedInput::extract_from_neo_input::<FSet::D, FSet::T, FSet::Z, I>(datetime);
Ok(FormattedDateTime {
pattern: self.selection.select(&datetime),
input: datetime,
names: self.names.as_borrowed(),
})
}
/// 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:
///
/// ```compile_fail
/// 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());
/// ```
pub fn format_any_calendar<'a, I>(&'a self, datetime: &I) -> FormattedDateTime<'a>
where
I: ?Sized + ConvertCalendar,
I::Converted<'a>: Sized + AllInputMarkers<FSet>,
{
let datetime = datetime.to_calendar(&self.calendar);
let datetime =
ExtractedInput::extract_from_neo_input::<FSet::D, FSet::T, FSet::Z, I::Converted<'a>>(
&datetime,
);
FormattedDateTime {
pattern: self.selection.select(&datetime),
input: datetime,
names: self.names.as_borrowed(),
}
}
}
impl<C: CldrCalendar, FSet: DateTimeMarkers> FixedCalendarDateTimeFormatter<C, FSet> {
/// Make this [`FixedCalendarDateTimeFormatter`] adopt a calendar so it can format any date.
///
/// This is useful if you need a [`DateTimeFormatter`] but know the calendar system ahead of time,
/// so that you do not need to link extra data you aren't using.
///
/// # Examples
///
/// ```
/// use icu::calendar::cal::Hebrew;
/// use icu::calendar::Date;
/// use icu::datetime::fieldsets::YMD;
/// use icu::datetime::FixedCalendarDateTimeFormatter;
/// use icu::locale::locale;
/// use writeable::assert_writeable_eq;
///
/// let formatter = FixedCalendarDateTimeFormatter::try_new(
/// locale!("en").into(),
/// YMD::long(),
/// )
/// .unwrap()
/// .into_formatter(Hebrew::new());
///
/// let date = Date::try_new_iso(2024, 10, 14).unwrap();
///
/// assert_writeable_eq!(
/// formatter.format_any_calendar(&date),
/// "12 Tishri 5785"
/// );
/// ```
pub fn into_formatter(self, calendar: C) -> DateTimeFormatter<FSet>
where
C: IntoAnyCalendar,
{
DateTimeFormatter {
selection: self.selection,
names: self.names,
calendar: calendar.to_any(),
}
}
/// Maps a [`FixedCalendarDateTimeFormatter`] of a specific `FSet` to a more general `FSet`.
///
/// For example, this can transform a formatter for [`YMD`] to one for [`DateFieldSet`].
///
/// [`YMD`]: crate::fieldsets::YMD
/// [`DateFieldSet`]: crate::fieldsets::enums::DateFieldSet
///
/// # Examples
///
/// ```
/// use icu::calendar::Gregorian;
/// use icu::calendar::DateTime;
/// use icu::datetime::FixedCalendarDateTimeFormatter;
/// use icu::datetime::fieldsets::{YMD, enums::DateFieldSet};
/// use icu::locale::locale;
/// use writeable::assert_writeable_eq;
///
/// let specific_formatter = FixedCalendarDateTimeFormatter::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(&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(&datetime),
/// "20 déc. 2024"
/// );
/// ```
pub fn with_fset<FSet2: DateTimeNamesFrom<FSet>>(
self,
) -> FixedCalendarDateTimeFormatter<C, FSet2> {
FixedCalendarDateTimeFormatter {
selection: self.selection,
names: self.names.with_fset(),
_calendar: PhantomData,
}
}
}
impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet> {
/// 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 { .. })));
/// ```
pub fn try_into_typed_formatter<C>(
self,
) -> Result<FixedCalendarDateTimeFormatter<C, FSet>, MismatchedCalendarError>
where
C: CldrCalendar + IntoAnyCalendar,
{
if let Err(cal) = C::from_any(self.calendar) {
return Err(MismatchedCalendarError {
this_kind: cal.kind(),
date_kind: None,
});
}
Ok(FixedCalendarDateTimeFormatter {
selection: self.selection,
names: self.names,
_calendar: PhantomData,
})
}
/// 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`].
///
/// [`YMD`]: crate::fieldsets::YMD
/// [`DateFieldSet`]: crate::fieldsets::enums::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"
/// );
/// ```
pub fn with_fset<FSet2: DateTimeNamesFrom<FSet>>(self) -> DateTimeFormatter<FSet2> {
DateTimeFormatter {
selection: self.selection,
names: self.names.with_fset(),
calendar: self.calendar,
}
}
/// 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");
/// ```
pub fn calendar_kind(&self) -> AnyCalendarKind {
self.calendar.kind()
}
}
/// A formatter optimized for time and time zone formatting.
///
/// # Examples
///
/// A [`TimeFormatter`] cannot be constructed with a fieldset that involves dates:
///
/// ```
/// use icu::datetime::TimeFormatter;
/// use icu::datetime::fieldsets::Y;
/// use icu::locale::locale;
///
/// assert!(TimeFormatter::try_new(locale!("und").into(), Y::medium()).is_err());
/// ```
///
/// Furthermore, it is a compile error in the format function:
///
/// ```compile_fail,E0271
/// use icu::datetime::TimeFormatter;
/// use icu::datetime::fieldsets::Y;
/// use icu::locale::locale;
///
/// let date: icu::calendar::Date<icu::calendar::Gregorian> = unimplemented!();
/// let formatter = TimeFormatter::try_new(locale!("und").into(), Y::medium()).unwrap();
///
/// // error[E0271]: type mismatch resolving `<Gregorian as AsCalendar>::Calendar == ()`
/// formatter.format(&date);
/// ```
pub type TimeFormatter<FSet> = FixedCalendarDateTimeFormatter<(), FSet>;
/// An intermediate type during a datetime formatting operation.
///
/// Not intended to be stored: convert to a string first.
#[derive(Debug)]
pub struct FormattedDateTime<'a> {
pattern: DateTimeZonePatternDataBorrowed<'a>,
input: ExtractedInput,
names: RawDateTimeNamesBorrowed<'a>,
}
impl Writeable for FormattedDateTime<'_> {
fn write_to_parts<S: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut S,
) -> Result<(), fmt::Error> {
let result = try_write_pattern_items(
self.pattern.metadata(),
self.pattern.iter_items(),
&self.input,
&self.names,
self.names.fixed_decimal_formatter,
sink,
);
// A DateTimeWriteError should not occur in normal usage because DateTimeFormatter
// guarantees that all names for the pattern have been loaded and that the input type
// is compatible with the pattern. However, this code path might be reachable with
// invalid data. In that case, debug-panic and return the fallback string.
match result {
Ok(Ok(())) => Ok(()),
Err(fmt::Error) => Err(fmt::Error),
Ok(Err(e)) => {
debug_assert!(false, "unexpected error in FormattedDateTime: {e:?}");
Ok(())
}
}
}
// TODO(#489): Implement writeable_length_hint
}
impl_display_with_writeable!(FormattedDateTime<'_>);
impl FormattedDateTime<'_> {
/// Gets the pattern used in this formatted value.
///
/// From the pattern, one can check the properties of the included components, such as
/// the hour cycle being used for formatting. See [`DateTimePattern`].
pub fn pattern(&self) -> DateTimePattern {
self.pattern.to_pattern()
}
}