Home > Web Front-end > JS Tutorial > body text

How to calculate the difference between two times using JS

亚连
Release: 2018-06-12 16:33:48
Original
3261 people have browsed it

This article mainly introduces the JS method of calculating the difference in minutes between two times, and analyzes the javascript conversion and calculation related operation skills for date and time in the form of a complete example. Friends who need it can refer to it

The example in this article describes the JS method of calculating the difference in minutes between two times. Share it with everyone for your reference. The details are as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>www.jb51.net js计算时间相差分钟数</title>
</head>
<body>
<script type="text/javascript" language="javascript">
function TimeDifference()
{
//定义两个变量time1,time2分别保存开始和结束时间
var time1="2017-12-02 12:25";
var time2="2017-12-03 12:35";
//判断开始时间是否大于结束日期
if(time1>time2)
{
  alert("开始时间不能大于结束时间!");
  return false;
}
//截取字符串,得到日期部分"2009-12-02",用split把字符串分隔成数组
var begin1=time1.substr(0,10).split("-");
var end1=time2.substr(0,10).split("-");
//将拆分的数组重新组合,并实例成化新的日期对象
var date1=new Date(begin1[1] + - + begin1[2] + - + begin1[0]);
var date2=new Date(end1[1] + - + end1[2] + - + end1[0]);
//得到两个日期之间的差值m,以分钟为单位
//Math.abs(date2-date1)计算出以毫秒为单位的差值
//Math.abs(date2-date1)/1000得到以秒为单位的差值
//Math.abs(date2-date1)/1000/60得到以分钟为单位的差值
var m=parseInt(Math.abs(date2-date1)/1000/60);
//小时数和分钟数相加得到总的分钟数
//time1.substr(11,2)截取字符串得到时间的小时数
//parseInt(time1.substr(11,2))*60把小时数转化成为分钟
var min1=parseInt(time1.substr(11,2))*60+parseInt(time1.substr(14,2));
var min2=parseInt(time2.substr(11,2))*60+parseInt(time2.substr(14,2));
//两个分钟数相减得到时间部分的差值,以分钟为单位
var n=min2-min1;
//将日期和时间两个部分计算出来的差值相加,即得到两个时间相减后的分钟数
var minutes=m+n;
document.writeln(minutes);
}
TimeDifference();
</script>
</body>
</html>
Copy after login

Running results: 1450

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Use Vue.set to dynamically add object attributes in Vue

There is no dev in vue2.0 -Configuration method under server.js

How to implement the file dragging and uploading function with progress bar in Vue

The above is the detailed content of How to calculate the difference between two times using 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