<div class="codetitle"> <span><a style="CURSOR: pointer" data="59218" class="copybut" id="copybut59218" onclick="doCopy('code59218')"><u>复制代码</u></a></span> 代码如下:</div> <div class="codebody" id="code59218"> <br><script type="text/javascript"> <BR>//计算一个日期字符串与当前日期相差值 <BR>//输入的参数形式如:2012-12-12 12:12:12 <BR>//返回相差值的字符串 <BR>function GetDateDiff(datetime) <BR>{ <BR>// 可以将2012 - 12 - 12 12 : 12 : 12字符串转为JS中的时期对象, <BR>// 因为默认情况下只把持2000 / 05 / 05这样形式的字符串转为时间对象 <BR>var dateBegin = new Date(datetime.replace(/-/g, "/")); <BR>var dateEnd = new Date(); <BR>var dateDiff = dateEnd.getTime() - dateBegin.getTime(); <BR>// 计算相差的天数 <BR>var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); <BR>var returnstr = ""; <BR>if(dayDiff > 2) //前天以前就直接返回时间字符串 <BR>{ <BR>return datetime; <BR>} <BR>else //前天以来的处理 <BR>{ <BR>var parttime = datetime.substring(11); <BR>switch (dayDiff) <BR>{ <BR>case 2 : <BR>returnstr += "前天 " + parttime; <BR>break; <BR>case 1 : <BR>returnstr += "昨天 " + parttime; <BR>break; <BR>default : //对今天的操作 <BR>var minuteleft = Math.floor(dateDiff / (60 * 1000)); //计算相差的分钟数 <BR>if(minuteleft > 30) <BR>{ <BR>returnstr += "今天 " + parttime; <BR>} <BR>else if (minuteleft == 0) <BR>{ <BR>returnstr += Math.floor(dateDiff / 1000) + "秒前"; <BR>} <BR>else <BR>{ <BR>returnstr += minuteleft + "分钟前"; <BR>} <BR>} <BR>alert(returnstr); <BR>return returnstr; <BR>} <BR>} <BR>☆其它备录: <BR>// <BR>//// 计算出小时数 <BR>// var leftSecond1 = dateDiff % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数 <BR>// var hourDiff = Math.floor(leftSecond1 / (3600 * 1000)) <BR>//// 计算相差分钟数 <BR>// var leftSecond2 = leftSecond1 % (3600 * 1000) // 计算小时数后剩余的毫秒数 <BR>// var minuteDiff = Math.floor(leftSecond2 / (60 * 1000)) <BR>//// 计算相差秒数 <BR>// var leftSecond3 = leftSecond2 % (60 * 1000) // 计算分钟数后剩余的毫秒数 <BR>// var secondDiff = Math.round(leftSecond3 / 1000) <BR>// var returnstr = ""; <BR>//function ToDate1(datetime) <BR>//{ <BR>// // 可以将20080808字符串转为JS中的时期对象 <BR>// return new Date(bd.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1/$2/$3")); <BR>//} <BR></script> <br> </div> <br>使用就简单了,直接引用这个函数就行了