JS Date String Formatter
by XstreamINsanity
HTML
<h2>Javascript Date String Formatter</h2>
<table id="dateExamples">
<thead>
<tr>
<td>Result</td>
<td>Date String</td>
<td>Delimiter</td>
<td>Year Format</td>
<td>Month Format</td>
<td>Day Format</td>
<td>Locale</td>
</tr>
</thead>
</table>
CSS
#dateExamples {
border-spacing:0;
}
#dateExamples tr td{
margin:0px;
padding:5px;
border:1px solid black;
text-align:center;
}
#dateExamples thead tr {
background-color:gray;
font-weight:bold;
}
JavaScript
makeExampleRows('12/12/2020');
makeExampleRows(null);
makeExampleRows(undefined);
makeExampleRows(undefined, '.');
makeExampleRows(undefined, undefined, undefined, undefined, undefined, 'en-US');
makeExampleRows(undefined, undefined, undefined, undefined, undefined, 'zh-HK');
makeExampleRows(undefined, undefined, '2-digit', undefined, undefined, 'en-US');
makeExampleRows(' ', undefined, '2-digit', undefined, undefined, 'en-US');
function formatDateOutput(
dateString,
dateDelimiter = '/',
yearFormat = 'numeric',
monthFormat = '2-digit',
dayFormat = '2-digit',
dateLocale = 'en-US')
{
if (dateString === null) throw Error(`${dateString} is an invalid date.`);
let dateFormat = new Intl.DateTimeFormat(dateLocale, { year: yearFormat, month: monthFormat , day: dayFormat }).format;
if (dateString === undefined) {
return dateFormat(dateString).replace(/\//g, dateDelimiter);
}
let trimmedDate = dateString.trim();
if (trimmedDate === '') throw Error(`Empty string is an invalid date.`);
let dateObj = new Date(trimmedDate);
let formattedDate = new Intl.DateTimeFormat(dateLocale, { year: yearFormat, month: monthFormat , day: dayFormat }).format(dateObj);
if (dateDelimiter === '/') return formattedDate;
return formattedDate.replace(/\//g, dateDelimiter);
};
function makeExampleRows(
exampleDate,
delimiterParam = undefined,
yearParam = undefined,
monthParam = undefined,
dayParam = undefined,
localeParam = undefined
)
{
const element = document.getElementById('dateExamples');
const newRow = document.createElement('tr');
let formattedResult = '';
try {
formattedResult = formatDateOutput(exampleDate, delimiterParam, yearParam, monthParam, dayParam, localeParam);
} catch (error) {
formattedResult = error;
}
addCellToRow(newRow, formattedResult);
addCellToRow(newRow, exampleDate);
addCellToRow(newRow, delimiterParam);
addCellToRow(newRow, yearParam);
...