In modern browsers (*), Date.prototype.toLocaleDateString()
allows you to define the formatting of a Date
in a convenient manner.
It requires the following format :
dateObj.toLocaleDateString([locales [, options]])
The locales
parameter should be a string with a BCP 47 language tag, or an array of such strings.
The options
parameter should be an object with some or all of the following properties:
"lookup"
and "best fit"
; the default is "best fit"
"UTC"
; the default is the runtime's default time zonetrue
and false
; the default is locale dependent"basic"
and "best fit"
; the default is "best fit"
"narrow"
, "short"
& "long"
"narrow"
, "short"
& "long"
"numeric"
& "2-digit"
"numeric"
, "2-digit"
, "narrow"
, "short"
& "long"
"numeric"
& "2-digit"
"numeric"
& "2-digit"
"numeric"
& "2-digit"
"numeric"
& "2-digit"
"short"
& "long"
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
});
Output if executed on January 24ᵗʰ, 2036 :
'24 Jan 2036'
If Date.prototype.toLocaleDateString()
isn't flexible enough to fulfill whatever need you may have, you might want to consider creating a custom Date object that looks like this:
var DateObject = (function() {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var date = function(str) {
this.set(str);
};
date.prototype = {
set : function(str) {
var dateDef = str ? new Date(str) : new Date();
this.day = dateDef.getDate();
this.dayPadded = (this.day < 10) ? ("0" + this.day) : "" + this.day;
this.month = dateDef.getMonth() + 1;
this.monthPadded = (this.month < 10) ? ("0" + this.month) : "" + this.month;
this.monthName = monthNames[this.month - 1];
this.year = dateDef.getFullYear();
},
get : function(properties, separator) {
var separator = separator ? separator : '-'
ret = [];
for(var i in properties) {
ret.push(this[properties[i]]);
}
return ret.join(separator);
}
};
return date;
})();
If you included that code and executed new DateObject()
on January 20ᵗʰ, 2019, it would produce an object with the following properties:
day: 20
dayPadded: "20"
month: 1
monthPadded: "01"
monthName: "January"
year: 2019
To get a formatted string, you could do something like this:
new DateObject().get(['dayPadded', 'monthPadded', 'year']);
That would produce the following output:
20-01-2016
(*) According to the MDN, "modern browsers" means Chrome 24+, Firefox 29+, IE11, Edge12+, Opera 15+ & Safari nightly build