In the previous article "How to use JavaScript to compare two dates", I introduced how to use JavaScript to compare two dates. Interested friends can read and learn~
The topic of this article is how to check whether a date is between two specified dates through javascript?
Below I will introduce to you two judgment implementation methods:
In the first method, we will use the .split() method and new Date() Constructor. In the second method, we will use the .getTime() method and the new Date() constructor.
The first method:
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> <style> body { text-align: center; } h1 { color: red; } #demo { font-weight: bold; } </style> </head> <body> <h1>PHP中文网</h1> <p> 日期 1 = "06/04/2019" 日期 2 = "07/10/2019" <br>待检查的日期 = "02/12/2019" </p> <button onclick="gfg_Run()"> 点击这里 </button> <p id="demo"></p> <script> var el_down = document.getElementById("demo"); // 格式- MM/DD/YYYY var Date_1 = "06/04/2019"; var Date_2 = "07/10/2019"; var Date_to_check = "02/12/2019"; function gfg_Run() { D_1 = Date_1.split("/"); D_2 = Date_2.split("/"); D_3 = Date_to_check.split("/"); var d1 = new Date(D_1[2], parseInt(D_1[1]) - 1, D_1[0]); var d2 = new Date(D_2[2], parseInt(D_2[1]) - 1, D_2[0]); var d3 = new Date(D_3[2], parseInt(D_3[1]) - 1, D_3[0]); if (d3 > d1 && d3 < d2) { el_down.innerHTML = "该日期在日期1和日期2之间 " ; } else { el_down.innerHTML = "该日期不在日期1和日期2之间 " ; } } </script> </body> </html>
The running effect is as follows:
##Second method:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> <style> body { text-align: center; } h1 { color:#ff7800; } #demo { font-weight: bold; } </style> </head> <body> <h1>PHP中文网</h1> <p> 日期 1 = "06/04/2019" 日期 2 = "07/10/2019" <br>待检查的日期 = "02/8/2019" </p> <button onclick="gfg_Run()"> 点击这里 </button> <p id="demo"></p> <script> var el_down = document.getElementById("demo"); // 格式 - MM/DD/YYYY var D1 = "06/04/2019"; var D2 = "07/10/2019"; var D3 = "02/8/2019"; function gfg_Run() { D1 = new Date(D1); D2 = new Date(D2); D3 = new Date(D3); if (D3.getTime() <= D2.getTime() && D3.getTime() >= D1.getTime()) { el_down.innerHTML = "该日期在日期1和日期2之间" ; } else { el_down.innerHTML = "该日期在日期1和日期2之间" ; } } </script> </body> </html>
Note:
split() method is used to split a string into a string array;
getTime()Method can return the number of milliseconds since January 1, 1970;
Date object is used to process date and time:
new Date()
var d = new Date(); var d = new Date(milliseconds); var d = new Date(dateString); var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
JavaScript Basic Tutorial》~Welcome everyone to learn~
The above is the detailed content of Determine whether a date is between two specified dates through js. For more information, please follow other related articles on the PHP Chinese website!