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").
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").
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 ;)