js版格式化输出时间

来源:互联网 发布:python特性 编辑:程序博客网 时间:2024/05/29 18:46

实现方式

通过js的原型方法,实现方法的扩展;
通过正则表达式匹配时间格式,然后替换为数据;利用正则表达式的其中一个好处是能够获取格式的长度信息,从而让数据格式化输出;

代码

if (!Date.prototype.Format) {    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;}

注:
1)RegExp.$1是RegExp的一个属性,指的是与正则表达式匹配的第一个 子匹配(以括号为标志)字符串,以此类推,RegExp.$2..RegExp.$99总共可以有99个匹配; 用于exec()或test()之后

Demo

var date = new date();console.log(date.Format("hh:mm:ss")); //输出23:57:14
0 0
原创粉丝点击