<html>
<head>
<script type="text/javascript">
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></head>
<body>

<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></body>
</html>

解决方案 »

  1.   

    不知道LZ的年份跟天数是怎么算的?var myDate=new Date();
    var begin = myDate.setFullYear("1987","11","8");
    var end = myDate.setFullYear("2011","11","30");  end - begin 得到的毫秒数慢慢算吧~~~!!!
    你非要考虑平年闰年、在写函数计算两个时间段的平年闰年数吧!!!
      

  2.   

    var today = new Date();
    var days;//离今天天数
    var months;//离今天月数
    var years;//离今天念书
    String birth = "1988-09-11"//生日
    var todayDay = today.getDate();//今天日期
    var todayMonth = today.getMonth+1;//今天月
    if(todayDay <=birthDay){
      days = todayDay+new Date(todayYear,todayMonth-1,0).getDate()-birthDay;
      todayMonth -= 1;
    }else{
      days = todayDay-birthday;
    }
    if(todayMonth<=birthMonth){
     months = todayMonth +12-birthMonth;
     year -=1
    }else{
     months = todayMonth-birthMonth;
    }
    years = todayYear-birthYear;
    没测试 不知道对不对唉