time-rs / time

The most used Rust library for date and time handling.
https://time-rs.github.io
Apache License 2.0
1.06k stars 261 forks source link

Make `format` methods localizable #680

Open tguichaoua opened 2 months ago

tguichaoua commented 2 months ago

It should be possible to make format methods localizable by passing a struct Localization with the month and weekday names. This struct is passed down to fmt_month and fmt_weekday methods that used it instead of the hardcoded MONTH_NAMES and WEEKDAY_NAMES.

pub struct Localization {
    pub month_names: [&[u8]; 12],
    pub weekday_names: [&[u8]; 7],
}

impl Localization {
    pub const EN: Self = Self { /* ... */ }
    pub const FR: Self = Self { /* ... */ }
    pub const DE: Self = Self { /* ... */ }
    pub const ES: Self = Self { /* ... */ }
     /* ... */
}

pub trait Sealed {
    fn format_into(
        &self,
        output: &mut impl Write,
        localization: &Localization,    // <-- new argument
        date: Option<Date>,
        time: Option<Time>,
        offset: Option<UtcOffset>
    ) -> Result<usize, Format>;

    fn format(
        &self,
        localization: &Localization,    // <-- new argument
        date: Option<Date>,
        time: Option<Time>,
        offset: Option<UtcOffset>
    ) -> Result<String, Format> { ... }
}

impl { Date, Time, ... } {
    pub fn format(self, format: &(impl Formattable + ?Sized)) -> Result<String, error::Format> {
        // Preserve the current behaviour
        self.format_localized(format, &Localization::EN)
    }

    pub fn format_localized(self, format: &(impl Formattable + ?Sized), localization: &Localization) -> Result<String, error::Format> {
        format.format(localization, Some(self), None, None)
    }
}
jhpratt commented 2 months ago

This is something I previously considered when I took over time in 2019. I was talked out of it at the time, though having basic support for localization is something I was recently reconsidering. The API wouldn't quite be what you have, but it wouldn't be that far off.

Mastermindaxe commented 1 month ago

@jhpratt Could you make a suggestion for the API? Currently on vacation and willing to take a crack at it if you can provide the general direction, which (as you said) isn't the above suggestion

Mastermindaxe commented 1 month ago

I could also just make a suggestion via a PR if that's preferred :D

jhpratt commented 1 month ago

For this specifically, I'd prefer not having a PR as it'll involve some code generation that will most likely end up in a separate repository.

Mastermindaxe commented 1 month ago

Gotcha! Any way I can help move this forward or support you with this?

jhpratt commented 1 month ago

Not really at this point. I have other priorities, so it's not going to happen in the immediate future.