<script language="javascript">
str1 = "2005-1-1 0:0:0:0";
str2 = "2002-2-2 1:1:1:1";
document.write(str1 + '与' + str2 + '的时间差为' +DiffLong(str1,str2));
//Get days and other datetime
//diffrence two datetime
// date1 :更早的日期 小的日期
// date2 :后面的日期 大的日期
// 返回两个时间差的天数小时数分数秒数和毫秒数
function DiffLong(datestr1,datestr2)
{
var date1 = ToDate(datestr1);
var date2 = ToDate(datestr2);
var datetimeTemp;
var isLater = true;
if(date1.getTime() > date2.getTime())
{
isLater = false;
datetimeTemp = date1;
date1 = date2;
date2 = datetimeTemp;
}
difference= date2.getTime() - date1.getTime();
thisdays = Math.floor(difference /(1000* 60 * 60*24));
difference = difference - thisdays * (1000*60*60*24);
thishours = Math.floor(difference/(1000* 60*60));
difference = difference - thishours * (1000*60*60);
thisminutes = Math.floor(difference/(1000* 60));
difference = difference - thisminutes * (1000*60);
thisseconds = Math.floor(difference/1000);
difference = difference - thisseconds * 1000;
thismillseconds = difference;
//document.write(date1 + 'only ' + thisdays + ' days until '+ date2 +'<P>');
//document.write(date1 + 'only ' + thishours + ' hours until '+ date2 +'<P>');
//document.write(date1 + 'only ' + thisminutes + ' minutes until '+ date2 +'<P>');
//document.write(date1 + 'only ' + thisseconds + ' seconds until '+ date2 +'<P>');
//document.write(date1 + 'only ' + thismillseconds + ' millisconds until '+ date2 +'<P>');
var strRet = thisdays + ' Days ' + thishours + ' hours ' +thisminutes + ' minutes ' + thisseconds + ' seconds ' + thismillseconds + ' milliseconds';
return strRet;
}
// Get Date string to date
// strdate: 2005-01-01 0:0:0:0
// it maybe easy by match.Regxp
//将一个标准化的时间字符串转换成为日期内型
function ToDate(strDate)
{
var thisDate = new Date();
thisArr = strDate.split(" ",2);
thisArr1 = thisArr[0].split("-",3);
thisDate.setYear(thisArr1[0]);
thisDate.setMonth(thisArr1[1]);
thisDate.setDate(thisArr1[2]);
thisArr2 = thisArr[1].split(":",4);
thisDate.setHours(thisArr2[0]);
thisDate.setMinutes(thisArr2[1]);
thisDate.setSeconds(thisArr2[2]);
thisDate.setMilliseconds(thisArr2[3]);
return thisDate;
}
</script>
<html>
<head>
<title>Test JavaScript about diff two datetime </title>
</head>
<body>
</body>
</html>