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

JavaScript implements date and time difference judgment

小云云
Release: 2018-03-03 09:19:35
Original
2214 people have browsed it

This article mainly introduces you to the method of judging the date and time difference in js. The article also introduces the code of js to find the time difference. Friends who need it can refer to it. I hope it can help you.

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

Related recommendations:

PHP calculates what day of the week a certain day is in a time period and how many days after the current time it is Days and date and time difference_PHP tutorial

php calculates the difference between two dates and times (returns year, month, day)

JS calculates the time from the current time Time difference technology sharing

The above is the detailed content of JavaScript implements date and time difference judgment. 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