A Better Javascript Date Format
HTML
<h2>Test Date Format Outputs</h2>
<ul id="res"></ul>
JavaScript
function addRow(id, content) {
var myDiv = document.createElement('li');
myDiv.className = 'row';
myDiv.innerHTML = content;
document.getElementById(id).appendChild(myDiv);
}
function consoleWrite(input){
addRow('res', input + '<br>');
}
// END FIDDLE HELPERS
function isValidDate(input)
{
return typeof input.getMonth === 'function';
}
// Because currently only arrays have .join
// Maybe there's a better way out there?
function joinObj(obj, seperator) {
var out = [];
for (k in obj) {
out.push(k);
}
return out.join(seperator);
}
function CountryCodeToDateFormat(countryInput)
{
// Written by Will Morrison 2018-04-05
//https://en.wikipedia.org/wiki/Date_format_by_country
//https://www.worldatlas.com/aatlas/ctycodes.htm
var countryFormatType = {
default: 'YYYY-MM-DD',
ISO8601: 'YYYY-MM-DD',
INTERNATIONAL: 'YYYY-MM-DD',
USA: 'M/d/yyyy',
GBR: 'd MMMM yyyy',
NLD: 'dd-MM-yyyy',
CHN: 'yy年MM月dd日'
// EXPAND ME!
}
if(!countryInput)
{
countryInput = "default";
}
if (!(countryInput in countryFormatType))
{
return countryInput;
}
// Build Regex Dynamically based on the list above.
// Should end up with something like this "/(INTERNATIONAL+|USA+|GBR+|CHN+)/g"
var countryMatchRegex = joinObj(countryFormatType, "|");
var regEx = new RegExp(countryMatchRegex,"g");
countryInput = countryInput.replace(regEx, function(countryCode) {
return countryFormatType[countryCode];
});
return countryInput;
}
function DateToString(inDate, formatString) {
// Written by Will Morrison 2018-04-05
// Validate that we're working with a date
if(!isValidDate(inDate))
{
inDate = new Date(inDate);
}
formatString = CountryCodeToDateFormat(formatString);
var dateObject = {
M: inDate.getMonth() + 1,
d: inDate.getDate(),
D: inDate.getDate(),
h: inDate.getHours(),
m: inDate.getMinutes(),
s: inDate.getSeconds(),
y:...