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

JS calculate date time difference

php中世界最好的语言
Release: 2018-03-17 13:10:21
Original
4439 people have browsed it

This time I will bring you JS to calculate the date and time difference. What are the precautions for JS to calculate the date and time difference? The following is a practical case, let's take a look.

The code for js to determine date and time is as follows:


alert(GetDateDiff("2018-02-27 19:20:22","2018-02-27 09:20:22","hour"));
function GetDateDiff(startTime, endTime, diffType) {
  //将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式 
  startTime = startTime.replace(/\-/g, "/");
  endTime = endTime.replace(/\-/g, "/");
  //将计算间隔类性字符转换为小写
  diffType = diffType.toLowerCase();
  var sTime =new Date(startTime); //开始时间
  var eTime =new Date(endTime); //结束时间
  //作为除数的数字
  var timeType =1;
  switch (diffType) {
    case"second":
      timeType =1000;
    break;
    case"minute":
      timeType =1000*60;
    break;
    case"hour":
      timeType =1000*3600;
    break;
    case"day":
      timeType =1000*3600*24;
    break;
    default:
    break;
  }
  return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(timeType));
}
Copy after login

PS: Let’s look at js to find the time difference

var date1=new Date(); //开始时间
alert("aa");
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+" 秒")
Copy after login

# I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to implement back force refresh on WeChat web side

How to use automatic generator in ionic2

Set cookie expiration to automatically update and automatically obtain

The above is the detailed content of JS calculate date time difference. 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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!