phensley / cldr-engine

Internationalization and localization in Typescript with Unicode CLDR, batteries included
https://phensley.github.io/cldr-engine/
Apache License 2.0
48 stars 3 forks source link

Get time interval with formatDateInterval #8

Open gmarty opened 1 year ago

gmarty commented 1 year ago

I'm trying to get a localised time interval using cldr.Calendars.formatDateInterval. It always returns the date no matter what skeleton I pass as an option. e.g.:

cldr.Calendars.formatDateInterval(
  start,
  end,
  {
    skeleton: 'Hmm',
    ca: 'gregory',
  }
)

Returns something like this with the ja language:

1/1 18:15~12/31 18:45

I'd like to get:

18:15~18:45
// Or even better:
18時15分~18時45分

When I look inside the language pack for Japanese, I see patterns like this one:

H時mm分~H時mm分

So it looks like the information is there, but somehow not surfaced.

I'd like to either have this function to comply more closely to the skeleton or a different function called cldr.Calendars.formatTimeInterval.

phensley commented 1 year ago

Hi @gmarty the behavior currently mimics the matching process described here in the standard. It attempts to find the "field of greatest difference" between the two dates, and combines that with the skeleton to select the most appropriate interval format. As a result, if two dates differ in the year, month or day, it will try to select an interval format to include those date fields.

A possible hack: if you know you only ever want to display intervals with hour and minute fields visible, you can copy the date fields to the end date, ensuring the field of greatest difference is one of the time fields:

const start = cldr.Calendars.toGregorianDate(new Date(2023, 0, 1, 12, 34, 56));
let end = cldr.Calendars.toGregorianDate(new Date(2023, 11, 31, 15, 37, 44));

// modify end date to fall on the same (year, month, day)
const { year, month, day } = start.fields();
end = end.set({ year, month, day });

s = cldr.Calendars.formatDateInterval(start, end, { skeleton: "Hmm" });
console.log(s);

//> en:   17:34 – 20:37
//> ja:   17時34分~20時37分
gmarty commented 1 year ago

I ended up using the hack you suggested and it works. Maybe you could add a little comment in the docs about it.