Last active
July 24, 2021 17:11
-
-
Save ashour/bcbdf1b50f7fa5cf004d9f84cfafdfd9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Options when formatting a date | |
*/ | |
interface DateFormatOptions { | |
includeYear?: Boolean; | |
} | |
/** | |
* For English, format a date with given options, adding an ordinal | |
* e.g. "May 1st, 1992" (note the "1st"). For non-English locales, | |
* format a date with given options (and no ordinal); | |
*/ | |
function formatLocalizedDateWithOrdinal(locale: Locale, | |
date: Date, | |
options: DateFormatOptions = { includeYear: false }) { | |
if (locale.toLowerCase().startsWith("en")) { | |
return formatEnglishDateWithOrdinal(date, options); | |
} | |
return formatNonEnglishDate(locale, date, options); | |
} | |
/** | |
* Format an English date with it ordinal e.g. "May 1st, 1992" | |
*/ | |
function formatEnglishDateWithOrdinal(date: Date, | |
{ includeYear }: DateFormatOptions): string { | |
const month: string = date.toLocaleDateString("en", { month: "long" }); | |
const day: string = getOrdinal(date.getDate()); | |
let formatted: string = `${month} ${day}`; | |
if (includeYear) { | |
formatted += `, ${date.getFullYear()}`; | |
} | |
return formatted; | |
} | |
/** | |
* Format a non-English date | |
*/ | |
function formatNonEnglishDate(locale: Locale, | |
date: Date, | |
{ includeYear }: DateFormatOptions): string { | |
const options: Intl.DateTimeFormatOptions = { day: "numeric", month: "long" }; | |
if (includeYear) { | |
options.year = "numeric"; | |
} | |
return date.toLocaleDateString(locale, options); | |
} | |
/** | |
* Retrieve an English ordinal for a number, e.g. "2nd" for 2 | |
*/ | |
function getOrdinal(n: number): string { | |
// From https://community.shopify.com/c/Shopify-Design/Ordinal-Number-in-javascript-1st-2nd-3rd-4th/m-p/72156 | |
var s=["th","st","nd","rd"], | |
v=n%100; | |
return n+(s[(v-20)%10]||s[v]||s[0]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment