Home >Web Front-end >JS Tutorial >How to compare time units in JS

How to compare time units in JS

php中世界最好的语言
php中世界最好的语言Original
2018-04-23 10:40:492024browse

This time I will bring you the method of comparing time units in JS. What are the precautions for comparing time units in JS? The following is a practical case, let’s take a look.

//时间比较(yyyy-MM-dd)
function compareDate(startDate, endDate) {
  var arrStart = startDate.split("-");
  var startTime = new Date(arrStart[0], arrStart[1], arrStart[2]);
  var startTimes = startTime.getTime();
  var arrEnd = endDate.split("-");
  var endTime = new Date(arrEnd[0], arrEnd[1], arrEnd[2]);
  var endTimes = endTime.getTime();
  if (endTimes<startTimes) {
    alert("结束时间不能小于开始时间");
    return false;
  }
  return true;
}
//时间比较(yyyy-MM-dd HH:mm:ss)
function compareTime(startTime,endTime) {
  var startTimes = startTime.substring(0, 10).split(&#39;-&#39;);
  var endTimes = endTime.substring(0, 10).split(&#39;-&#39;);
  startTime = startTimes[1] + &#39;-&#39; + startTimes[2] + &#39;-&#39; + startTimes[0] + &#39; &#39; + startTime.substring(10, 19);
  endTime = endTimes[1] + &#39;-&#39; + endTimes[2] + &#39;-&#39; + endTimes[0] + &#39; &#39; + endTime.substring(10, 19);
  var thisResult = (Date.parse(endTime) - Date.parse(startTime)) / 3600 / 1000;
  if (thisResult < 0) {
    alert("endTime小于tartTime!");
  } else if (thisResult > 0) {
    alert("endTime大于tartTime!");
  } else if (thisResult == 0) {
    alert("endTime等于tartTime!");
  } else {
    return &#39;异常&#39;;
  }
}

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

Other related articles!

Recommended reading:

How to hide js code

Summary of experience using JS

!=, ==, !==, === usage summary

The above is the detailed content of How to compare time units in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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