<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>日期计算</title>
<script src="./jquery1.6.2.js" type="text/javascript"></script>
<style>
.error{color:red}
</style>
<script type="text/javascript">
var intervalID = 0;
function calculate(inputTime){
var now = new Date();
var t = new Date(inputTime);
var past = (inputTime < now.getTime()) ? 1 : 0; //输入的时间过去了就是1,否则为0
var difference = 0; //差值
//下面的差值减去八个小时,是因为new Date(0)是"Thu Jan 1 08:00:00 UTC+0800 1970",从八点开始算的
if(past) difference = new Date(now.getTime() - inputTime - 8 * 3600 * 1000);
else difference = new Date(inputTime - now.getTime() - 8 * 3600 * 1000);
//计算过去的天数、小时、分钟和秒。天数要自己算,其它的get就行了
var dDays = parseInt(difference.getTime() / 3600 / 24 /1000);
var dHours = difference.getHours();
var dMinutes =difference.getMinutes();
var dSeconds = difference.getSeconds();
$("#output").html([
"现在时间是:<font color='blue'>", now.toLocaleString(),"</font>,","<br />",
"<font color='blue'>", t.toLocaleString(),"</font>",
["还要", "已经过去了"][past],
"<font color='blue'>",dDays, "天", dHours, "小时", dMinutes, "分钟", dSeconds, "秒","</font>",
["才到", ""][past]
].join(""));//用join方法将上面的数组连接起来
}
function btn_calculate(){
clearInterval(intervalID);
$("#error").className = null;
var t = new Date($("#t").val());
if(t.getTime().toString() == "NaN"){ //如果输入的时间不对,则将提示字符设置为error,即红色
$("#error").className = "error";
$("#t").select();
return false;
}
intervalID = setInterval("calculate(" + t.getTime() + ")", 1000); //设置定时器,每秒钟执行一次calculate函数
return false;
}
</script>
</head>
<body>
<form onsubmit="return btn_calculate()">
<div><span id="error">请输入要计算的时间(格式:2010/02/01 23:07,省略时分秒则是00:00:00):</span>
<input id="t" value="2010/02/01 23:07" /> <input type="submit" value="计算时间">
</div><br />
<div id="output"></div><!--输出区域-->
</body>
</html>