Not a full-proof solution but can but use as a reference and you can add support for new formats.
Logic
- Create a date object for a specific date that will exist for every year. Like: 31/12/2016
- Now search first non alphanumeric character. This is your delimiter.
- Now that you have 3 parts, you can find
dd
easily by comparing value to 31
.
- Even year part is easy, since it can have 2 values,
16
or 2016
.
- Month can be tricky. It can have
12
or Dec
or December
. For that you can have 2 checks. If number and equal to 12, it mm
. If not number and length is 3, its mmm
else mmmm
Now you can create var d = new Date('2016/12/31')
and pass d.toLocaleDateString()
to below function.
function getDateFormat(dateStr) {
var delimiter = dateStr.match(/[^0-9a-z]/i)[0];
var dateParts = dateStr.split(delimiter);
var r = dateParts.map(function(d, i) {
if (d == 31) {
return "dd"
} else if (!isNaN(d) && (d == 2016 || (d + 2000) == 2016)) {
return d.toString().length === 4 ? "YYYY" : "yy"
} else if (d == 12) {
return "mm"
} else if (isNaN(d)) {
var _t = d.replace(/[^a-z]/gi, '')
return _t.length === 3 ? "mmm" : "mmmm"
}
});
return r.join(delimiter);
}
Date.prototype.getSystemDateFormat = function(){
return getDateFormat(new Date('2016/12/31').toLocaleDateString());
}
//or
Date.prototype.SYSTEM_FORMAT = (function(){
return getDateFormat(new Date('2016/12/31').toLocaleDateString());
})()
console.log(new Date().getSystemDateFormat())
console.log(new Date().SYSTEM_FORMAT)
var d1 = "12/31/2016"
console.log(getDateFormat(d1))
d1 = "31/12/2016"
console.log(getDateFormat(d1))
d1 = "31 December 2016"
console.log(getDateFormat(d1))
d1 = "31 Dec. 2016"
console.log(getDateFormat(d1))
d1 = "31-12-2016"
console.log(getDateFormat(d1))
d1 = "31.12.2016"
console.log(getDateFormat(d1))
You can also add functions to date.prototype to get value directly instead of calling it every time,
Date.prototype.getSystemDateFormat = function(){
return getDateFormat(new Date('2016/12/31').toLocaleDateString());
}
//or
Date.prototype.SYSTEM_FORMAT = (function(){
return getDateFormat(new Date('2016/12/31').toLocaleDateString());
})()
Edit 1
As correctly pointed out by @RobG, date.toLocaleString or date.toLocaleDateString are not uniform across all browsers. They are not supported by < IE11. So this is not a reliable answer. You can use it for reference though.