typescript 添加基础类型的扩展方法

以时间转换为案例:

//声明接口,也是在声明date这个基础类型要定义一个format的扩展方法,不写接口声明会报错
interface Date {
    Format(fmt:string):string;
}

//要写到class类的外面,不然会划红线报错
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;
}

调用:

value.CreateTime = new Date(value.CreateTime).Format('yyyy-MM-dd');

posted @ 2019-03-05 14:27  洛晨随风  阅读(5482)  评论(0编辑  收藏  举报