Swamy Reddy
Swamy Reddy

Reputation: 51

How to get the date format based on locale using Intl.DateTimeFormat in JavaScript

I want to get the standard date format (like MM/DD/YYYY) of the date based on given local id. But below code is not giving the format. Please help how I can get the date format.

var dateFormat = new Intl.DateTimeFormat("as-IN").

Upvotes: 4

Views: 2894

Answers (2)

cevelry
cevelry

Reputation: 49

Here is a very basic loop returns remote sense locale:

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

Upvotes: 0

Uroš Križman
Uroš Križman

Reputation: 19

What I did was to first format a dummy date based on the locale. Then I would replace distinct date parts (day, month, year) with the standard placeholders DD, MM, YYYY.

This is the code:

/**
 * Returns date format used by Intl.DateTimeFormat (for specified `options`).
 * Example for Serbia: `DD/MM/YYYY`
 *
 * **Note** that this will always return the two decimal format for day and month and four for year (e.g. `DD/MM/YYYY`)
 */
export function getIntlDateFormatForLocale(locale: string, options?: Intl.DateTimeFormatOptions) {
  const year = 2222
  const month = 12
  const day = 15
  const date = new Date(year, month - 1, day)
  const formattedDate = new Intl.DateTimeFormat(locale, options).format(date)
  return formattedDate.replace(`${year}`, 'YYYY').replace(`${month}`, 'MM').replace(`${day}`, 'DD')
}

Please note that the format you get out of this is for two-digit representation of date parts. This means that if the user has a single-digit locale set up, using this format will yield two-digit date parts.

E.g.: If a user locale outputs dates like 1/1/2021, it will be formatted as 01/01/2021 when using the format from this function.

It will also not work correctly when format outputs weekdays (e.g. Mon), Mandarin/Japanese/Arabic digits, etc.

There might be some other caveats, but for my use-case, this was good enough ;)

Upvotes: 1

Related Questions