Home > Web Front-end > JS Tutorial > How to find the example code to find the time difference in js

How to find the example code to find the time difference in js

怪我咯
Release: 2017-07-16 10:51:47
Original
1719 people have browsed it

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));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template