jsは二つのdate時間の差を計算します.

2085 ワード

 
 
 
  
 



var v=new Date();

function test(){
	v.setFullYear(txt_Y.value);
	v.setMonth(txt_M.value-1);
	v.setDate(txt_D.value);
	v.setHours(txt_H.value);
	v.setMinutes(txt_Min.value);
	v.setSeconds(0);
	var now = new Date();
	var ressult = getDateCha(v,now);
	if(!ressult.error){
		show.innerHTML +=( 
		"["+v.toLocaleDateString()+" "+v.toLocaleTimeString()+"] "
		+"   "+
		"["+now.toLocaleDateString()+" "+now.toLocaleTimeString()+"]======"
		+ (ressult.toString())+"<br/>");
	}
}


/*                             
*@param  beginDate         
*@param endDate       ,    ,         ,default=new Date()
*@retrun JSON      :D、H、M、S、error( ,  ,  , ,         abs,        error)
*beginDate       endDate(    )
****/
var getDateCha=function(beginDate,endDate){
	var res={D:0,H:0,M:0,S:0,abs:true,error:false};
	//      :        Date  ,         ,   new Date()
	if(typeof(endDate)=="undefined" || null== endDate||""==endDate ){endDate = new Date();}
	if( !(beginDate instanceof (Date)) ||  !(endDate instanceof (Date))){
		res.error=true;//"       ";
		return res;
	}

	//    ,         。
	if(beginDate>endDate){
		var tempDate = beginDate;
		beginDate = endDate;
		endDate=tempDate;
		res.abs=false;//  beginDate  endDate
	}
	var chaTime =(endDate.getTime()-beginDate.getTime());
	
	var Day_Param  =1000*60*60*24;//       
	var Hour_Param = 1000*60*60;//        
	res.D =Math.floor(chaTime/(Day_Param));//

	chaTime = chaTime-res.D*Day_Param;//       。      
	res.H = Math.floor(chaTime/(Hour_Param));
	chaTime = chaTime-res.H*Hour_Param;//        。      
	res.M = Math.floor(chaTime/(1000*60));
	res.S=(chaTime-res.M*1000*60)/1000;//        。      
	//alert(res.S);

	res.toString=function(){
		return this.D+" "+this.H+"  "+this.M+"  ";
	};
	return res;
	
}