Useful little JavaScript toYMD Function

I forget where I first saw this, but I’m using it frequently these days, so I thought I would post it up and maybe save someone some time in the future:

Date.prototype.toYMD = function() {
       var year, month, day;
       year = String(this.getFullYear());
       month = String(this.getMonth() + 1);
       if (month.length == 1) {
           month = "0" + month;
       }
       day = String(this.getDate());
       if (day.length == 1) {
           day = "0" + day;
       }
       return year + "-" + month + "-" + day;
    };

Now you can do this:

var date = new Date();
alert(date.toYMD());

Not the most exciting piece of code, but it can be rather handy. Try it out here, if you want.

This entry was posted in jQuery / Javascript, Web Development and tagged , . Bookmark the permalink.

Leave a Reply

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