codice:
Date.prototype.LOCALIZED_MONTHS = new Array(
"Gennaio", "Febbraio", "Marzo", "Aprile",
"Maggio", "Giugno", "Luglio", "Agosto",
"Settembre", "Ottobre", "Novembre", "Dicembre"
);
Date.prototype.LOCALIZED_DAYS = new Array(
"Domenica", "Lunedì",
"Martedì", "Mercoledì",
"Giovedì", "Venerdì", "Sabato"
);
String.prototype.nf = function(c)
{
return this.length < c ? ("0" + this).nf(c) : this;
}
Array.prototype.ss = function(i, exp, rep)
{
var it = this[i].split(exp);
if (it.length > 1)
{
for (var c = 1; c < it.length; c+=2)
it.splice(c, 0, rep);
eval("this.splice(i, 1, '" + it.join("','") + "')");
}
}
Date.prototype.format = function(pattern)
{
var ps = pattern.split("'");
if (ps.length % 2 == 0) return "";
for (var i = 1; i < ps.length - 1; i++)
{
if (ps[i] == "")
{
ps[i-1] += "'" + ps[i+1];
ps.splice(i, 2);
}
}
for (var i = 0; i < ps.length; i+=2)
{
ps.ss(i, /y{3,}/, this.getFullYear());
ps.ss(i, /yy/, ("" + this.getFullYear()).substring(2));
ps.ss(i, /y/, this.getFullYear());
ps.ss(i, /M{4,}/, this.LOCALIZED_MONTHS[this.getMonth()]);
ps.ss(i, /MMM/, this.LOCALIZED_MONTHS[this.getMonth()].substring(0, 3));
ps.ss(i, /MM/, ("" + this.getMonth()).nf(2));
ps.ss(i, /M/, this.getMonth());
ps.ss(i, /d{2,}/, ("" + this.getDate()).nf(2));
ps.ss(i, /d/, this.getDate());
ps.ss(i, /E{4,}/, this.LOCALIZED_DAYS[this.getDay()]);
ps.ss(i, /EEE/, this.LOCALIZED_DAYS[this.getDay()].substring(0, 3));
ps.ss(i, /EE/, ("" + this.getDay()).nf(2));
ps.ss(i, /E/, this.getDay());
ps.ss(i, /H{2,}/, ("" + this.getHours()).nf(2));
ps.ss(i, /H/, this.getHours());
ps.ss(i, /m{2,}/, ("" + this.getMinutes()).nf(2));
ps.ss(i, /m/, this.getMinutes());
ps.ss(i, /s{2,}/, ("" + this.getSeconds()).nf(2));
ps.ss(i, /s/, this.getSeconds());
ps.ss(i, /S{3,}/, ("" + this.getMilliseconds()).nf(3));
ps.ss(i, /SS/, ("" + this.getMilliseconds()).nf(2));
ps.ss(i, /S/, this.getMilliseconds());
ps.ss(i, /a+/, this.getHours() < 12 ? "AM" : "PM");
ps.ss(i, /K{2,}/, (this.getHours() <= 12 ? "" + this.getHours() : "" + (this.getHours - 12)).nf(2));
ps.ss(i, /K/, (this.getHours() <= 12 ? this.getHours() : this.getHours - 12));
}
return ps.join("");
}
Le stringhe da passare come pattern seguono le regole della già citata classe Java, le trovate su: