JavaScript Date 字符串格式化

被JavaScript灵活性惊艳到了,记录下。

Date.prototype.yyyymmdd = function () {   
    var yyyy = this.getFullYear().toString();    
    var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based   
    var dd = this.getDate().toString();    
    return yyyy + (mm[1] ? mm : "0" + mm[0]) + (dd[1] ? dd : "0" + dd[0]); // padding
};
Date.prototype.mmdd = function () {    
    var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based    
    var dd = this.getDate().toString();   
    return mm + '月' + dd + '日';};
Date.prototype.hhii = function () {   
     var hh = this.getHours().toString();
     var ii = this.getMinutes().toString();
     return hh + ':' + (ii[1] ? ii : "0" + ii[0]);
};

神奇的地方来了:

var d = new Date();
console.log(d.yyyymmdd()); //输出20160603
console.log(d.mmdd()); //输出6月3日
console.log(d.hhii()); //输出9:59

两段代码可以粘贴在Chrome的Console中执行,即可看到效果。

你可能感兴趣的:(JavaScript Date 字符串格式化)