Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
52
rated 0 times [  56] [ 4]  / answers: 1 / hits: 31239  / 15 Years ago, fri, june 12, 2009, 12:00:00

How do I format this date so that the alert displays the date in MM/dd/yyyy format?



<script type=text/javascript>
var date = new Date();
alert(date);
</script>

More From » date

 Answers
26

You prototype a method so you never have to do this irritating task again:



Date.prototype.toFormattedString = function (f)
{
var nm = this.getMonthName();
var nd = this.getDayName();
f = f.replace(/yyyy/g, this.getFullYear());
f = f.replace(/yy/g, String(this.getFullYear()).substr(2,2));
f = f.replace(/MMM/g, nm.substr(0,3).toUpperCase());
f = f.replace(/Mmm/g, nm.substr(0,3));
f = f.replace(/MM*/g, nm.toUpperCase());
f = f.replace(/Mm*/g, nm);
f = f.replace(/mm/g, String(this.getMonth()+1).padLeft('0',2));
f = f.replace(/DDD/g, nd.substr(0,3).toUpperCase());
f = f.replace(/Ddd/g, nd.substr(0,3));
f = f.replace(/DD*/g, nd.toUpperCase());
f = f.replace(/Dd*/g, nd);
f = f.replace(/dd/g, String(this.getDate()).padLeft('0',2));
f = f.replace(/d*/g, this.getDate());
return f;
};


(and yes you could chain those replaces, but it's not here for readability before anyone asks)






As requested, additional prototypes to support the above snippet.



Date.prototype.getMonthName = function ()
{
return this.toLocaleString().replace(/[^a-z]/gi,'');
};

//n.b. this is sooo not i18n safe :)
Date.prototype.getDayName = function ()
{
switch(this.getDay())
{
case 0: return 'Sunday';
case 1: return 'Monday';
case 2: return 'Tuesday';
case 3: return 'Wednesday';
case 4: return 'Thursday';
case 5: return 'Friday';
case 6: return 'Saturday';
}
};

String.prototype.padLeft = function (value, size)
{
var x = this;
while (x.length < size) {x = value + x;}
return x;
};


and usage example:



alert((new Date()).toFormattedString('dd Mmm, yyyy'));

[#99327] Monday, June 8, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;