JavaScript Method for comparing whether the current time is within a specified time period

  • 2021-07-07 06:12:55
  • OfStack

This article illustrates JavaScript's method of comparing whether the current time is within a specified time period. Share it for your reference, as follows:


function checkTime(stime, etime) {
  // Start time 
  var arrs = stime.split("-");
  var startTime = new Date(arrs[0], arrs[1], arrs[2]);
  var startTimes = startTime.getTime();
  // End time 
  var arre = etime.split("-");
  var endTime = new Date(arre[0], arre[1], arre[2]);
  var endTimes = endTime.getTime();
  // Current time 
  var thisDate = new Date();
  var thisDates = thisDate.getFullYear() + "-0" + (thisDate.getMonth() + 1) + "-" + thisDate.getDate();
  var arrn = thisDates.split("-");
  var nowTime = new Date(arrn[0], arrn[1], arrn[2]);
  var nowTimes = nowTime.getTime();
  if (nowTimes < startTimes || nowTimes > endTimes) {
    return false;
  }
  return true;
}
// Usage: 
var timebool=checkTime('2016-8-1','2016-8-10');// Note: Date with " - "Separation 
if(timebool==true){
  document.write(' The current date is within the specified time period ');
}else{
  document.write(' The current date is not within the specified time period ');
}

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: