Get string format for date based on locale

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.

Upvotes: 1

Views: 837

Answers (2)

cevelry
cevelry

Reputation: 49

Here is a very basic loop returns remote sense locale:

            let dd ='';
            for(let i=0;i<new Intl.DateTimeFormat(navigator.language).formatToParts().length;i++){
                if(new Intl.DateTimeFormat(navigator.language).formatToParts()[i].type === "year") {
                    dd += "yyyy";
                } else if(new Intl.DateTimeFormat(navigator.language).formatToParts()[i].type === "literal"){
                    dd += new Intl.DateTimeFormat(navigator.language).formatToParts()[i].value;
                } else if(new Intl.DateTimeFormat(navigator.language).formatToParts()[i].type === "day") {
                    dd += "dd";
                } else if(new Intl.DateTimeFormat(navigator.language).formatToParts()[i].type === "month") {
                    dd += "MM";
                }
            }
            console.log(dd);

Upvotes: 0

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('');
};

Upvotes: 1

Related Questions