Home > Article > Web Front-end > How to find the example code to find the time difference in js
In fact, javascriptThe way to calculate the time difference is very simple. If it is the default Date() type, the direct subtraction is the number of milliseconds.
If what you get is not a date type, but a string format like "2016-03-28 10:27:00", then you need to convert the string first Convert to date type.
The following will bring you an implementation code for js to find the time difference.
var date1=new Date(); //开始时间 var date2=new Date(); //结束时间 var date3=date2.getTime()-date1.getTime() //时间差的毫秒数 //计算出相差天数 var days=Math.floor(date3/(24*3600*1000)) //计算出小时数 var leave1=date3%(24*3600*1000) //计算天数后剩余的毫秒数 var hours=Math.floor(leave1/(3600*1000)) //计算相差分钟数 var leave2=leave1%(3600*1000) //计算小时数后剩余的毫秒数 var minutes=Math.floor(leave2/(60*1000)) //计算相差秒数 var leave3=leave2%(60*1000) //计算分钟数后剩余的毫秒数 var seconds=Math.round(leave3/1000) alert(" 相差 "+days+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒") Math.floor(Math.abs(k1 - k2) / 1000 / 60 / 60 /24 + 0.5);//时间差四舍五入 document.write("两位小数点:"+a.toFixed(2)+"<br>四位小数点"+a.toFixed(4));
The above is the detailed content of How to find the example code to find the time difference in js. For more information, please follow other related articles on the PHP Chinese website!