一:计算两个日期相差的天数
1 <html> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 4 <title></title> 5 </head> 6 7 <body> 8 <button onClick="btnCount_Click()">计算相差天数</button> 9 <script language="JavaScript"> 10 11 function btnCount_Click(){ 12 s1 = "2002-1-10" 13 s2 = "2002-10-1" 14 alert(DateDiff(s1,s2)) 15 } 16 17 //计算天数差的函数,通用 18 function DateDiff(sDate1, sDate2){ //sDate1和sDate2是2002-12-18格式 19 var aDate, oDate1, oDate2, iDays 20 aDate = sDate1.split("-") 21 oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为12-18-2002格式 22 aDate = sDate2.split("-") 23 oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) 24 iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24) //把相差的毫秒数转换为天数 25 return iDays 26 }
二:计算一定天数后的日期
1 <script language="javascript" type="text/javascript"> 2 var startDate = new Date (); 3 var intValue = 0; 4 var endDate = null; 5 6 intValue = startDate.getTime(); i 7 ntValue += 100 * (24 * 3600 * 1000); 8 endDate = new Date (intValue); 9 alert (endDate.getFullYear()+"-"+ (endDate.getMonth()+1)+"-"+ endDate.getDate()); 10 </script>
上面的100代表100天后的日期,你可以修改。JS中Date.getTime(),只能1970.01.01之后的日期;还有月份是0 - 11,有点不一样,切忌哦。当然你也可以计算特定日期后的日期。
1 <script language="javascript" type="text/javascript"> 2 var startDate = new Date (2007, (8-1), 1, 10, 10, 10); 3 var intValue = 0; 4 var endDate = null; 5 6 intValue = startDate.getTime(); 7 intValue += 100 * (24 * 3600 * 1000); 8 endDate = new Date (intValue); 9 alert (endDate.getFullYear()+"-"+ (endDate.getMonth()+1)+"-"+ endDate.getDate()); 10 </script>
两个日期之间的倒计时
//传入4个参数 年月日 以及 事件显示的 div的名字(id) var abc = 1000; function ShowCountDown(year,month,day,contDown){ var now = new Date(); var endDate = new Date(year, month-1, day); var leftTime=endDate.getTime()-now.getTime(); var leftsecond = parseInt(leftTime/1000); //两个时期之间相差的毫秒数 var day1=Math.floor(leftsecond/(60*60*24)); //两个日期相差的天数 var hour=Math.floor((leftsecond-day1*24*60*60)/3600); //减去当前显示的天数 计算剩下需要显示的小时,分钟,秒 var minute=Math.floor((leftsecond-day1*24*60*60-hour*3600)/60); var second=Math.floor(leftsecond-day1*24*60*60-hour*3600-minute*60); var cc = $('.' + contDown); //传入变量需要加 加号 //console.log(cc.length); cc.children(".day").text(day1).css("color","#f00"); cc.children(".hour").text(hour).css("color","#f00"); cc.children(".minute").text(minute).css("color","#f00"); cc.children(".second").text(second).css("color","#f00"); }; /*------------------- 进行封装 ----------------------------------*/ $(function(){ setInterval("ShowCountDown(2016,7,20,'contDown1')",abc); setInterval("ShowCountDown(2016,6,20,'contDown2')",abc); });
<p class="contDown2">
<span class="day"></span>
<span class="hour"></span>
<span class="minute"></span>
<span class="second"></span>
</p>