First, you need to set up functions to return the day and month names, since the JS Date object doesn't include them:
Date._dayNames = new Array(
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday");
Date._dayNamesA = new Array(
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat");
Date.prototype.getDayName = function(abbreviate)
{
if (isNaN(this))
return "";
else if (true == abbreviate)
return Date._dayNamesA[this.getDay()];
else
return Date._dayNames[this.getDay()];
}
Date._monthNames = new Array(
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December");
Date._monthNamesA = new Array(
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"June",
"July",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec");
Date.prototype.getMonthName = function(abbreviate)
{
if (isNaN(this))
return "";
else if (true == abbreviate)
return Date._monthNamesA[this.getMonth()];
else
return Date._monthNames[this.getMonth()];
}
Then, you need to use a regular expression to parse the format string and substitute the real values:
Date._reFormat = /(\\{0,1})(dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|gg|g|hh|h|ss|f+|tt|t|zzz|zz|z)/gi;
Date.prototype.format = function(format)
{
if (isNaN(this)) return this.toString();
if (!format || 0 == format.length) return this.toString();
var value = this;
return format.replace(Date.\_reFormat, function($0, $1, $2)
{
var fmt = $2;
if (!fmt || 0 == fmt.length) return "";
var ret = "";
if ("\\\\" == $1)
{
ret = fmt.charAt(0);
fmt = fmt.substr(1);
if (0 == fmt.length) return ret;
}
switch(fmt.toLowerCase())
{
case "dddd":
{
// Full day name
ret += value.getDayName();
break;
}
case "ddd":
{
// Short day name
ret += value.getDayName(true);
break;
}
case "dd":
{
// Padded day number
var d = value.getDate();