Topic: JavaScript date formatting

I am just starting to dig into JavaScript as a programming language and I am trying to do some date formatting.  I found a few examples, but many of them seemed to be a little more complicated than what I really need.

Here is what I ended up with:

String.prototype.lpad = function(padString, desiredLength)
{
	var i;
	var paddedString = "";

	for (i=this.length; i< desiredLength; i++)
	{
		paddedString = paddedString.concat(padString);
	}
	
	paddedString = paddedString.concat(this);
	
	return paddedString;
}

Date.prototype.toString = function(format)
{
	var year = this.getFullYear().toString();
	var month = (this.getMonth() + 1).toString();
	var day = this.getDate().toString();

	format = format.replace(/yyyy/, year);
	format = format.replace(/yy/, year.substr(2, 2));
	format = format.replace(/mm/, month.lpad("0", 2));
	format = format.replace(/m/, month);
	format = format.replace(/dd/, day.lpad("0", 2));
	format = format.replace(/d/, day);
	
	return format;	
}

//call like this: myDate.toString("mm/dd/yyyy");

It seems to work fine for what I need it to do.  Do any of you more experienced JavaScripters have any suggestions or notice any glaring problems?

Thanks,
Eric

Re: JavaScript date formatting

It's easier for me to work with a demo of it, so I put it together on my site and I can't seem to get it to do much.  Am I calling this correctly?

http://chris-barr.com/files/datetest.html

Re: JavaScript date formatting

I have been calling it like this:

Today's date is: <script type="text/javascript">
var todaysDate = new Date();
document.write(todaysDate.toString("mm/dd/yyyy"));</script>
<br />
The first of the month is: <script type="text/javascript">
document.write((new Date("04/01/2008").toString("yyyy-mm-dd")));</script>

Re: JavaScript date formatting

There we go, that's the missing information I needed.

Yep, it seems to work nicely.