joanllenas / ngx-date-fns

⏳ date-fns pipes for Angular
163 stars 14 forks source link

Auto-detect language #404

Closed perotom closed 5 months ago

perotom commented 5 months ago

I want to auto-detect the formatting based on user language. I find myself writing a configuration factory like:

import {de, enGB, enUS, fr, it} from 'date-fns/locale';

const dateLocaleFactory = () => {
  const lang = navigator.language;
  if (lang.startsWith('en')) {
    if (lang === 'en-GB') {
      return enGB;
    } else {
      return enUS;
    }
  } else if (lang.startsWith('de')) {
    return de;
  } else if (lang.startsWith('it')) {
    return it;
  } else if (lang.startsWith('fr')) {
    return fr;
  } else { // default
    return enUS;
  }
};
const dateConfigFactory = () => {
  const c = new DateFnsConfigurationService();
  c.setLocale(dateLocaleFactory());
  return c;
};

I wonder if there is a helper function or better way of implementing all available languages? I know date-fns is written in a way to not import all locale but it would be great to have a function which would ease the process of auto-detecting the language. Are there some ideas or better ways to solve it instead of a giant if else?

joanllenas commented 5 months ago

Hi @perotom , I did a quick experiment, and I came up with this: https://stackblitz.com/edit/stackblitz-starters-am9ztj?file=src%2Fmain.ts But it doesn't make much of a difference.

Maybe you can come up with something by examining this document: https://github.com/date-fns/date-fns/blob/main/docs/webpack.md#removing-unused-languages-from-dynamic-import

If you do, please share your findings here! This is an interesting problem to solve.

Thanks

perotom commented 5 months ago

I see, thanks for the information!