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

How to determine date and time difference in JavaScript

亚连
Release: 2018-06-02 10:30:59
Original
1924 people have browsed it

This article introduces you to the method of JS to determine the date and time difference through example code. The article also introduces the code of JS to determine the time difference. Friends who need it can refer to it.

The code of JS to determine the date and time is as follows Instructions:

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

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

Related articles:

Installation tutorial for using vue and element components (detailed tutorial)

Use JS code to make QR code and Generate function (detailed tutorial)

A brief discussion on how vue.js imports css library (elementUi)

The above is the detailed content of How to determine date and time difference in JavaScript. 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