date-picker-svelte icon indicating copy to clipboard operation
date-picker-svelte copied to clipboard

Automatically infer locales

Open Tropix126 opened this issue 2 years ago • 5 comments

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 avatar Feb 18 '22 15:02 Tropix126

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.

Tropix126 avatar Feb 18 '22 17:02 Tropix126

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

probablykasper avatar Feb 18 '22 17:02 probablykasper

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?

Tropix126 avatar Feb 18 '22 19:02 Tropix126

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

probablykasper avatar Feb 18 '22 22:02 probablykasper

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)

probablykasper avatar Feb 20 '22 20:02 probablykasper