日期格式化

如何将new Date()出来的数据格式化?

var time = nea Date();

var validityTime = time.format("yyyy-MM-dd");


调用format函数:

/ 日期格式化: new Date().format('yyyy-MM-dd HH:mm:ss EEE');
Date.prototype.format = Date.prototype.format || function( pattern ) {
    var o = {
        "M+" : this.getMonth()+1, //月份
        "d+" : this.getDate(), //日
        "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
        "H+" : this.getHours(), //小时
        "m+" : this.getMinutes(), //分
        "s+" : this.getSeconds(), //秒
        "q+" : Math.floor( (this.getMonth()+3)/3 ), //季度
        "S" : this.getMilliseconds() //毫秒
    };
    var week = {
        "0" : "\u65e5",
        "1" : "\u4e00",
        "2" : "\u4e8c",
        "3" : "\u4e09",
        "4" : "\u56db",
        "5" : "\u4e94",
        "6" : "\u516d"
    };
    var day = {
        "today" : "\u4eca\u5929",
        "tomorrow" : "\u660e\u5929",
        "houday" : "\u540e\u5929"
    };
    if(/(y+)/.test( pattern )){
        pattern = pattern.replace( RegExp.$1, ( this.getFullYear()+"" ).substr( 4 - RegExp.$1.length ) );
    }
    if(/(E+)/.test( pattern )){
        var tmp = ( ( RegExp.$1.length>1 ) ? ( RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468" ) : "" )+week[this.getDay()+""] ;
        pattern = pattern.replace( RegExp.$1, tmp);
    }

    var date = new Date(this.getFullYear() + '/' + (this.getMonth()+1) + '/' + this.getDate());
    var today = new Date(new Date().getFullYear()+'/'+(new Date().getMonth()+1)+'/'+new Date().getDate());
    var tomorrow = new Date((new Date()).setDate(today.getDate()+1));
    tomorrow.setHours(0);
    tomorrow.setMinutes(0);
    tomorrow.setSeconds(0);
    var houday = new Date((new Date()).setDate(today.getDate()+2));
    houday.setHours(0);
    houday.setMinutes(0);
    houday.setSeconds(0);
    if(/(D+)/.test( pattern )){
        var iDate = Math.floor(date.getTime()/1000);
        var iToday = Math.floor(today.getTime()/1000);
        var iTomorrow = Math.floor(tomorrow.getTime()/1000);
        var iHouday = Math.floor(houday.getTime()/1000);
        var tmp = '';
        if(iDate == iToday){
            tmp = day['today'];
        }else if(iDate == iTomorrow){
            tmp = day['tomorrow'];
        }else if(iDate == iHouday){
            tmp = day['houday'];
        }
        pattern = pattern.replace( RegExp.$1, tmp);
    }
    for(var k in o){
        if(new RegExp("("+ k +")").test(pattern)){
            pattern = pattern.replace( RegExp.$1, ( RegExp.$1.length == 1 ) ? ( o[k] ) : ( ("00"+ o[k]).substr((""+ o[k]).length) ) );
        }
    }
    return pattern;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值