js Simple Time Comparison Method

  • 2021-07-07 06:16:24
  • OfStack

In this paper, an example is given to describe the method of simple time comparison of js. Share it for your reference, as follows:


// Time comparison ( 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(" End time cannot be less than start time ");
    return false;
  }
  return true;
}
// Time comparison ( yyyy-MM-dd HH:mm:ss ) 
function compareTime(startTime,endTime) {
  var startTimes = startTime.substring(0, 10).split('-');
  var endTimes = endTime.substring(0, 10).split('-');
  startTime = startTimes[1] + '-' + startTimes[2] + '-' + startTimes[0] + ' ' + startTime.substring(10, 19);
  endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + endTime.substring(10, 19);
  var thisResult = (Date.parse(endTime) - Date.parse(startTime)) / 3600 / 1000;
  if (thisResult < 0) {
    alert("endTime Less than tartTime ! ");
  } else if (thisResult > 0) {
    alert("endTime Greater than tartTime ! ");
  } else if (thisResult == 0) {
    alert("endTime Equal to tartTime ! ");
  } else {
    return ' Anomaly ';
  }
}

PS: Friends who are interested in JavaScript time and date operation can also refer to this online tool:

Unix timestamp (timestamp) conversion tool:
http://tools.ofstack.com/code/unixtime

Online time query around the world:
http://tools.ofstack.com/zhuanhuanqi/worldtime

Online perpetual calendar:
http://tools.ofstack.com/bianmin/wannianli

Page perpetual calendar calendar:
http://tools.ofstack.com/bianmin/webwannianli

For more information about JavaScript, please see the topics of this site: "Summary of JavaScript Time and Date Operation Skills", "Summary of JavaScript Switching Special Effects and Skills", "Summary of JavaScript Search Algorithm Skills", "Summary of JavaScript Animation Special Effects and Skills", "Summary of JavaScript Error and Debugging Skills", "Summary of JavaScript Data Structure and Algorithm Skills", "Summary of JavaScript Traversal Algorithm and Skills" and "Summary of JavaScript Mathematical Operation Usage"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: