probablykasper / date-picker-svelte

Date and time picker for Svelte
https://date-picker-svelte.kasper.space
MIT License
313 stars 65 forks source link

Automatically infer locales #8

Open Tropix126 opened 2 years ago

Tropix126 commented 2 years ago

The Intl.DateTimeFormat API has a few neat utilities for date-specific localization, including ones that can be used by this component to simplify locales. Additionally when a provided local is not specified/undefined, it will automatically return data based on the user's navigator.language making it ideal for this sort of thing. It also means that there's no hardcoding or date formatting libraries required (I think).

function getDays(locale) {
    const { format } = new Intl.DateTimeFormat(locale, {
        weekday: "short"
    });
    return [...Array(7).keys()].map(day => format(new Date(Date.UTC(2000, 1, day))));
}

getDays(); // returns based on navigator.language. e.g. ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
getDays("ja-JP"); // returns a specific hardcoded locale. e.g. ["日","月","火","水","木","金","土"]
function getMonths(locale) {
    const { format } = new Intl.DateTimeFormat(locale, {
        month: "long"
    });
    return [...Array(12).keys()].map(month => format(new Date(2000, month)));
}

getMonths(); // returns based on navigator.language. e.g. ["January","February","March","April","May","June","July","August","September","October","November","December"]
getMonths("ja-JP"); // returns a specific hardcoded locale. e.g. ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]

In this setup, the consumer of the library can simply provide a locale string and have the browser automatically output a localized array. It also means that if no locale is specified (through props, I guess) the datepicker will use the user's system language without any bundle overhead from a library like date-fns.

Tropix126 commented 2 years ago

This also doesn't need to be a breaking change. The locale prop could accept either an Intl locale string, or a custom object like what's being used right now.

probablykasper commented 2 years ago

Sounds like a good idea, but I'm not sure if the weekday names would work. It seems you can only get M or Mon, but I think ideally we would have Mo

Tropix126 commented 2 years ago

Sounds like a good idea, but I'm not sure if the weekday names would work. It seems you can only get M or Mon, but I think ideally we would have Mo

Hmm, yeah. This does seem to be consistent with how date-fns handles locales. Do you know if this only an issue with english languages?

probablykasper commented 2 years ago

date-fns supports all three, M, Mo and Mon. I don't think it's anything specific to english

probablykasper commented 2 years ago

Could work to add a utility function for this for people who are fine with the weekdays being M or Mon (can be an option to choose between them)