Javascript Date toFormattedString(format)

Description

Javascript Date toFormattedString(format)



Date.prototype.toFormattedString = function (format) {

    var year = (this.getFullYear()).toString();
    var month = (1 + this.getMonth()).toString();
    var day = (this.getDate()).toString();

    month = month.length > 1 ? month : "0" + month;
    day = day.length > 1 ? day : "0" + day;

    switch (format) {
        case "YYYYMMDD": return year + month + day; break;
        case "YYYY-MM-DD": return year + "-" + month + "-" + day; break;
        case "YYYY.MM.DD": return year + "." + month + "." + day; break;
        case "DDMMYYYY": return day + month + year; break;
        case "MMDDYYYY": return month + day + year; break;
        case "MM-DD-YYYY": return month + "-" + day + "-" + year; break;
        case "MM/DD/YYYY": return month + "/" + day + "/" + year; break;
    }/*  ww w .  j  a  v  a2  s. com*/

    throw { message: "Unsupported date format" };

}



PreviousNext

Related