My approach involved initially creating a dummy date in accordance with the locale. Subsequently, I proceeded to substitute specific date components (day, month, year) with the standard placeholders DD
, MM
, YYYY
.
Below is the code snippet:
/**
* Returns date format utilized by Intl.DateTimeFormat (for specified `options`).
* Example for Serbia: `DD/MM/YYYY`
*
* **Note** that this will consistently output the two-digit format for day and month along with four digits 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')
}
Important to mention: The resulting format from this function presents date parts in their two-digit form. Therefore, if a user's locale displays single-digit dates, using this format will result in double-digit representations.
For instance: If a user's locale generates dates like 1/1/2021
, it will be transformed into 01/01/2021
when applying the format obtained from this function.
This method may not yield accurate results when the format contains weekdays (e.g. Mon
), Mandarin/Japanese/Arabic numerals, etc.
While there might be certain limitations, this solution sufficed for my particular requirements ;)