年<input id="txt_Y" value="2011"/>
月<input id="txt_M" value="2"/>
日<input id="txt_D" value="26"/>
小时<input id="txt_H" value="13"/>
分<input id="txt_Min" value="0"/>
<br/>
<input type="button" onclick="test();"value="测试">
<div id="show">
<!--展示测试结果-->
</div>
<script> 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; } </script>