收集两个计算时间差的计算方法代码片段:
1 var date1=new Date(); //开始时间 2 var date2=new Date(); //结束时间 3 var date3=date2.getTime()-date1.getTime() //时间差的毫秒数 4 5 ------------------------------ 6 7 //计算出相差天数 8 var days=Math.floor(date3/(24*3600*1000)) 9 10 //计算出小时数11 12 var leave1=date3%(24*3600*1000) //计算天数后剩余的毫秒数13 var hours=Math.floor(leave1/(3600*1000))14 //计算相差分钟数15 var leave2=leave1%(3600*1000) //计算小时数后剩余的毫秒数16 var minutes=Math.floor(leave2/(60*1000))17 //计算相差秒数18 var leave3=leave2%(60*1000) //计算分钟数后剩余的毫秒数19 var seconds=Math.round(leave3/1000)20 alert(" 相差 "+days+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒")
第二段代码:
1 var minute = 1000 * 60; 2 var hour = minute * 60; 3 var day = hour * 24; 4 var halfamonth = day * 15; 5 var month = day * 30; 6 7 function getDateDiff(dateTimeStamp){ 8 var now = new Date().getTime(); 9 var diffValue = now - dateTimeStamp;10 11 if(diffValue < 0){12 //非法操作13 //alert("结束日期不能小于开始日期!");14 }15 16 var monthC =diffValue/month;17 var weekC =diffValue/(7*day);18 var dayC =diffValue/day;19 var hourC =diffValue/hour;20 var minC =diffValue/minute;21 22 if(monthC>=1){23 result="发表于" + parseInt(monthC) + "个月前";24 }25 else if(weekC>=1){26 result="发表于" + parseInt(weekC) + "个星期前";27 }28 else if(dayC>=1){29 result="发表于"+ parseInt(dayC) +"天前";30 }31 else if(hourC>=1){32 result="发表于"+ parseInt(hourC) +"个小时前";33 }34 else if(minC>=1){35 result="发表于"+ parseInt(minC) +"分钟前";36 }else37 result="刚刚发表";38 ? return result;39 }
引用地址: