检查日期自今天起30天以上

Pra*_*att 14 javascript jquery jquery-ui

我正在使用jQuery datepicker并试图找出今天日期和所选日期之间的区别,但是遇到问题......而不是问题......我无法完美地找到它...

我尝试在'onSelect event of datepicker'上做这个

问题:如何使用jQuery Datepicjer检查所选日期是否超过今天的30天?

任何帮助将不胜感激....!!注意:不想使用任何库,我需要通过仅使用jQuery来解决这个问题.

Cer*_*rus 36

获取30天后的时间戳:

var timestamp = new Date().getTime() + (30 * 24 * 60 * 60 * 1000)
//                                      day hour  min  sec  msec
Run Code Online (Sandbox Code Playgroud)

将该时间戳与所选日期的时间戳进行比较.

if (timestamp > selectedTimestamp) {
    // The selected time is less than 30 days from now
}
else if (timestamp < selectedTimestamp) {
    // The selected time is more than 30 days from now
}
else {
    // -Exact- same timestamps.
}
Run Code Online (Sandbox Code Playgroud)

  • 固体代码,但OP似乎要求未来30天,而不是30天前.对我而言,它只是一个标志变化,但可能想澄清未来的绊脚石. (2认同)

小智 5

我为您创建了一个示例。

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
  <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>
</head>
<body>

Date: <input type="text" id="thedate"/>
<div id="checkDate">Check Date</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

和 Js

$('#thedate').datepicker();

$('#checkDate').bind('click', function() {
  var selectedDate = $('#thedate').datepicker('getDate');
  var today = new Date(); 
  var targetDate= new Date();
  targetDate.setDate(today.getDate()+ 30);
  targetDate.setHours(0);
  targetDate.setMinutes(0);
  targetDate.setSeconds(0);

  if (Date.parse(targetDate ) >Date.parse(selectedDate)) {
    alert('Within Date limits');
  } else {
    alert('not Within Date limits');
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以在此处在线查看此代码