Date 自定义方法

有时咱们须要对日期格式化,这时能够利用javascript 的prototype机制进行扩展。javascript

以下,咱们为Date对象增长了一个Format方法,接受一个格式化参数,返回格式化后的日期字符串。java

Date.prototype.Format = function (fmt) { //author: meizz
            var o = {
                "M+": this.getMonth() + 1, //月份
                "d+": this.getDate(), //日
                "H+": this.getHours(), //小时
                "m+": this.getMinutes(), //分
                "s+": this.getSeconds(), //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }

咱们能够像使用java日期格式化同样来来使用这个方法。this

new Date().Format("yyyy-MM-dd")
new Date().Format("yyyy-MM-dd HH:mm:ss")
相关文章
相关标签/搜索