I am trying to get the format string for dates like "dd/MM/yyyy" based on locale. I want to use it in a picker date component to change the default format based on language.
I have a solution but I would like others if is possible.
function getDateFormatPattern(locale: string) {
const getPatternForPart = (part: Intl.DateTimeFormatPart) => {
switch (part.type) {
case 'day':
return 'd'.repeat(part.value.length);
case 'month':
return 'M'.repeat(part.value.length);
case 'year':
return 'y'.repeat(part.value.length);
case 'literal':
return part.value;
}
};
return new Intl.DateTimeFormat(locale).formatToParts(new Date('2022-01-01'))
.map(getPatternForPart)
.join('');
};