简体   繁体   中英

How can I restrict dates to some number of days from some date?

I would like to ask how to restrict the mindate/maxdate from a selected date.

For example, I have two datepicker, picker_A and picker_B.

I selected 2020/01/29 in picker_A. Then, I need to restrict the date range in picker_B to allow only 10 days before/after "2020/01/29" can be selected in picker_B.

Thank you very much.

this code use jquery datepicker method for assign datepicker to your controls.

I use minDate and maxDate properties to set date range.

for calculate 10 days before selected date:

var minDate = new Date(maxDate - (10 * 86400000));

1 Hour = 3600 seconds 24 Hours = 86400 seconds.

but we need miliseconds. so: 86400 * 1000 = 86400000 ms. 10 * 86400000 = 10 Days

 $(function () { $("#From").datepicker({ format: 'yyyy-mm-dd', constrainInput: true, onSelect: function (date) { var maxDate = new Date(date); var minDate = new Date(maxDate - (10 * 86400000)); $('#To').datepicker('destroy').datepicker({ format: 'yyyy-mm-dd', minDate: minDate, maxDate: maxDate, onSelect: function (date) { console.log(date); } }).datepicker('setDate', maxDate); } }).datepicker('setDate', new Date()); var maxDate = new Date(); var minDate = new Date(maxDate - (10 * 86400000)); $('#To').datepicker({ format: 'yyyy-mm-dd', minDate: minDate, maxDate: maxDate, onSelect: function (date) { console.log(date); } }).datepicker('setDate', maxDate); });
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" type="text/css"> <link href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" rel="stylesheet" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script> </head> <body> <p> <input id="From" type="text" /> <input id="To" type="text" /> </p> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM