Format dates

This commit is contained in:
Savanni D'Gerinel 2024-02-29 09:48:19 -05:00
parent 245f9d0997
commit d95dd4de50
1 changed files with 49 additions and 20 deletions

View File

@ -121,13 +121,20 @@ impl L10N {
}
*/
fn format_date(
&self,
time: NaiveDate,
date_style: length::Date,
time_style: length::Time,
) -> String {
unimplemented!()
fn format_date(&self, date: NaiveDate, date_style: length::Date) -> String {
let formatter = icu::datetime::DateFormatter::try_new_with_length(
&DataLocale::from(&self.locale),
date_style,
)
.unwrap();
let icu_date: icu::calendar::Date<icu::calendar::Gregorian> =
icu::calendar::Date::try_new_gregorian_date(
date.year(),
date.month().try_into().unwrap(),
date.day().try_into().unwrap(),
)
.unwrap();
formatter.format_to_string(&icu_date.to_any()).unwrap()
}
fn format_f64(&self, value: f64) -> String {
@ -172,7 +179,20 @@ impl From<DateTime> for icu::calendar::DateTime<icu::calendar::Gregorian> {
mod tests {
use super::*;
fn reftime() -> DateTime {
fn ref_l10n() -> L10N {
let mut l10n = L10N::default();
// Make sure we know the locale before the test begins. Some systems, such as my own, are
// not actually in English.
l10n.set_locale("en-US".to_owned());
l10n.set_timezone(chrono_tz::US::Eastern);
l10n
}
fn ref_date() -> NaiveDate {
NaiveDate::from_ymd_opt(2006, 1, 2).unwrap()
}
fn ref_time() -> DateTime {
NaiveDate::from_ymd_opt(2006, 1, 2)
.unwrap()
.and_hms_opt(3, 4, 5)
@ -184,12 +204,8 @@ mod tests {
#[test]
fn it_formats_a_time_in_utc() {
let mut l10n = L10N::default();
// Make sure we know the locale before the test begins. Some systems, such as my own, are
// not actually in English.
l10n.set_locale("en-US".to_owned());
l10n.set_timezone(chrono_tz::US::Eastern);
let now = reftime();
let mut l10n = ref_l10n();
let now = ref_time();
// 202f is the code-point for a narrow non-breaking space. Presumably this is used in
// particular to ensure that the am/pm marker doesn't get split off from the time
@ -207,12 +223,8 @@ mod tests {
#[test]
fn it_formats_a_time_in_the_current_zone() {
let mut l10n = L10N::default();
// Make sure we know the locale before the test begins. Some systems, such as my own, are
// not actually in English.
l10n.set_locale("en-US".to_owned());
l10n.set_timezone(chrono_tz::US::Eastern);
let now = reftime();
let mut l10n = ref_l10n();
let now = ref_time();
// 202f is the code-point for a narrow non-breaking space. Presumably this is used in
// particular to ensure that the am/pm marker doesn't get split off from the time
@ -228,6 +240,23 @@ mod tests {
);
}
#[test]
fn it_formats_dates() {
let mut l10n = ref_l10n();
let today = ref_date();
assert_eq!(
l10n.format_date(today.clone(), length::Date::Long),
"January 2, 2006"
);
l10n.set_locale("eo-EO".to_owned());
assert_eq!(
l10n.format_date(today.clone(), length::Date::Long),
"2006-Januaro-02"
);
}
#[test]
fn it_formats_a_number_according_to_locale() {
unimplemented!()