格式化日期和时间

//格式化日期
var months=["Jan", "Feb", "Mar", "Apr", "May","Jun","Jul","Aug","Sep","Oct","Nov", "Dec"];

function formatDate(time){
	if(!time){
		return "";
	}

	var reg = /^(\d{4})-(\d{2})-(\d{2})$/;
	if(reg.test(time)){
		return time;
	}
	if(typeof time=='number'){
		var d=new Date(time);
		var dStr = "";
		var mStr = "";
		if(d.getDate()<10){
			dStr = "0"+d.getDate();
		}else{
			dStr = d.getDate();
		}
		if(d.getMonth()<9){ //month should +1
			mStr = "0" + (d.getMonth()+1);
		}else{
			mStr = (d.getMonth()+1);
		}
		return d.getFullYear()+'-'+mStr+'-'+dStr;
	}else{
		var str=time.split('-');
		if(str[1].indexOf('0')==0){
			str[1]=str[1].substring(1);
		}
		return months[parseInt(str[1])-1]+" "+str[2]+" "+str[0];
	}
}


//格式化日期时间
function formatTime(time){
	//debugger;
	if(!time){
		return "";
	}
	if(typeof time=='number'){
		var d=new Date(time);
		var dStr = "";
		var mStr = "";
		var hStr = "";
		var miStr = "";
		var seStr ="";
		
		if(d.getDate()<10){//日
			dStr = "0"+d.getDate();
		}else{
			dStr = d.getDate();
		}
		if(d.getMonth()<9){ //month should +1
			mStr = "0" + (d.getMonth()+1);
		}else{
			mStr = (d.getMonth()+1);
		}
		if(d.getHours()<10){
			hStr="0"+(d.getHours()); 
			
		}else{
			hStr=d.getHours();
		}
		if(d.getMinutes()<10){
			miStr="0"+d.getMinutes();
		}else{
			miStr=d.getMinutes();
		}
		if(d.getSeconds()<10){
			seStr="0"+d.getSeconds();
		}else{
			seStr=d.getSeconds();
		}
		return d.getFullYear()+'-'+mStr+'-'+dStr+' '+hStr+':'+miStr+':'+seStr;
	}else{
		var str=time.split('-');
		if(str[1].indexOf('0')==0){
			str[1]=str[1].substring(1);
		}
		return months[parseInt(str[1])-1]+" "+str[2]+" "+str[0];
	}
}

  

posted @ 2016-05-24 16:07  黑土白云  阅读(271)  评论(0编辑  收藏  举报