A week ago someone asked me how they can format a date so that it returns the MM/DD/YYYY format. The following is a definition for a function that does just that:


// Definition for the toMMDDYYYY() function of all dates.
Date.prototype.toMMDDYYYY = function(delimiter) {
  return isNaN(this.getTime()) ? this + "" : [("0" + (this.getMonth() + 1)).slice(-2), ("0" + this.getDate()).slice(-2), this.getFullYear()].join(delimiter == null ? "/" : delimiter);
};

The following code is an example of how you would use this code:


var aDayIn03 = new Date(2003, 11, 01);  // December 1, 2003
alert(aDayIn03.toMMDDYYYY());  // 12/01/2003
alert(aDayIn03.toMMDDYYYY("-"));  // 12-01-2003

The following is a JSBin page which gives you the ability to test this function out yourself:
Date.prototype.toMMDDYYYY()

A more convenient way to format dates is actually to just use library code such as is available here in jPaq.

P.S. A special thanks go out to ildar for pointing out that I can use slice() to save time if running thousands of times. By using the slice function instead of the regular expression approach and also the join() function, I was able to shorten the amount of code used as well.


1 Comment

ildar · September 12, 2012 at 4:58 AM

Instead of

stringObject.replace(/0(..-)/g, “$1”)

use the following code

stringObject.slice(-2)

It is shorter and faster.

Leave a Reply

Your email address will not be published. Required fields are marked *