JonSnow
JonSnow

Reputation: 325

jquery UI datepicker: calculate minDate x years from today

Good afternoon

I am trying to set the minDate for a jQuery UI datepicker, which should be valid for all users aged between 12 and 17. With maxDate alone this works fine. And I know I have to calculate the minDate somehow. I have searched all the other StackOverflow threads, but have not been able to find something similar. The other solutions I have found set a fixed date, but I need it alwyas 12-17 years compared with today.

What I have tried so far:

minDate: new Date((currentYear - 12), currentMonth, currentDay))

and

minDate: "-12y"

My current sample:

$(".datepicker").datepicker({
    numberOfMonths: 1,
    firstDay: 1,
    defaultDate: 0,
    changeMonth: true,
    changeYear: true,
    yearRange: '1910:c',
    dateFormat: 'dd.mm.yy',
    beforeShow: function () {
        var currentYear = (new Date).getFullYear();
        var currentMonth = (new Date).getMonth() + 1;
        var currentDay = (new Date).getDate();
        
        $(this).datepicker({ 
            minDate: new Date((currentYear - 12), currentMonth, currentDay),
            maxDate: "-17y -11m -30d"
        });
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

<input type="text" class="datepicker" id="myDate">

Upvotes: 1

Views: 854

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

minDate: "-12y" works absolutely fine, however if you want to only allow ages between 12 and 17 you need to use both minDate and maxDate to set the allowed range.

Due to this your use of onBeforeShow() is redundant, along with numberOfMonths, defaultDate and yearRange. Try this:

$(".datepicker").datepicker({
  firstDay: 1,
  changeMonth: true,
  changeYear: true,
  dateFormat: 'dd.mm.yy',
  minDate: '-17y', // min 17 years ago
  maxDate: '-12y', // max 12 years ago
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<input type="text" class="datepicker" id="myDate">

Upvotes: 2

Related Questions