Skip to content

Instantly share code, notes, and snippets.

@sidisinsane
Created June 18, 2023 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidisinsane/75dc548e244cf97930ee1b999836bd3f to your computer and use it in GitHub Desktop.
Save sidisinsane/75dc548e244cf97930ee1b999836bd3f to your computer and use it in GitHub Desktop.
Formats a date with internationalization.
/**
* @typedef {Object} I18nFormatDateType - creates a new type named "I18nFormatDateType"
* @property {string} [dateString] - The string representation of the date to be formatted. Defaults to current date.
* @property {string} [locale="en-US"] - The locale (keyof typeof Intl.Locale) to use for formatting the date.
* @property {Intl.DateTimeFormatOptions} [formatOptions] - The options for formatting the date.
*/
/**
* Formats a date with internationalization.
*
* @param {I18nFormatDateType} options - The options for formatting the date.
* @returns {string} - The formatted date string.
*
* @example
*
* const formattedDate = i18nFormatDate({
* dateString: "2023-06-10",
* locale: "de",
* formatOptions: { day: "numeric", month: "long", year: "numeric" }
* });
* console.log(formattedDate); // Output: "10. Juni 2023"
*/
export function i18nFormatDate(options) {
const defaultFormatOptions = {
day: "2-digit",
month: "short",
year: "numeric",
};
const {
dateString,
locale = "en-US",
formatOptions = defaultFormatOptions,
} = options;
const date = dateString ? new Date(dateString) : new Date();
if (dateString && isNaN(date.getTime())) {
console.error(`Invalid date: ${dateString}`);
return dateString;
}
return new Intl.DateTimeFormat(locale, formatOptions).format(date);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment