How to install and use locale to vanilla js date range picker?

413 Views Asked by At

I am using vanilla js datepicker. I want to set the names of the months it displays to a different language.

I have an Object with the names but I have no clue how to make it work.

Object with names:

var localeDict = {
            days: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota"],
            daysShort: ["Niedz.", "Pon.", "Wt.", "Śr.", "Czw.", "Piąt.", "Sob."],
            daysMin: ["Ndz.", "Pn.", "Wt.", "Śr.", "Czw.", "Pt.", "Sob."],
            months: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"],
            monthsShort: ["Sty.", "Lut.", "Mar.", "Kwi.", "Maj", "Cze.", "Lip.", "Sie.", "Wrz.", "Paź.", "Lis.", "Gru."],
            today: "Dzisiaj",
            weekStart: 1,
            clear: "Wyczyść",
            format: "dd.mm.yyyy"
        };

And here I build a datepicker object:

datepicker = new DateRangePicker(picker_div, {
          format: "dd.mm.yyyy",
          language: "pl",
          maxDate: new Date(),
          months: localeDict.months,
          todayHighlight: true,
        });

I have tried setting option months, monthNames, nothing works. The names stay in English, as default. I tried assigning these options to particular datepickers inside date range picker, but nothing worked.

I can't find a solution in the documentation, whatever works there does not seem to work in my case.

Or: maybe I should use a different library?

1

There are 1 best solutions below

3
Kaddath On BEST ANSWER

The process to do it is explained in the i18n section:

After the library is imported to your script (so that the global object Datepicker exists), you can add your language directly to Datepicker.locales, like this:

Datepicker.locales.pl = {
    days: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota"],
    daysShort: ["Niedz.", "Pon.", "Wt.", "Śr.", "Czw.", "Piąt.", "Sob."],
    daysMin: ["Ndz.", "Pn.", "Wt.", "Śr.", "Czw.", "Pt.", "Sob."],
    months: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"],
    monthsShort: ["Sty.", "Lut.", "Mar.", "Kwi.", "Maj", "Cze.", "Lip.", "Sie.", "Wrz.", "Paź.", "Lis.", "Gru."],
    today: "Dzisiaj",
    weekStart: 1,
    clear: "Wyczyść",
    format: "dd.mm.yyyy"
};

You need to do this only once, after the library is imported. Then you should be able to use:

language: "pl",

in you DateRangePicker options as you did. This should be enough, no need to add any months options.

You can also place this locale in a separate file and import it, as it is specified in the documentation, I won't extend on this but you already can find a file for pl here: https://cdn.jsdelivr.net/npm/[email protected]/dist/js/locales/pl.js as commented