日期格式化

来源:互联网 发布:制作视频mp4软件 编辑:程序博客网 时间:2024/05/22 13:50

如何将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;}