New to Telerik UI for ASP.NET Core? Download free 30-day trial

Enabling Only Dates in a Specific Date Range using DateTime Picker in {{ site.framework }}

Environment

| Product | Date/Time Pickers for ASP.NET Core | | Version | 2023.3.1114 |

Description

I want to select a DateTime between the current date and the following 30 days using the DateTime Picker in ASP.NET Core. I would like to restrict the selection to only dates within this range and disable dates outside of it.

Solution

To achieve this, you need to utilize the DisableDates handler functionality of the DateTimePicker in ASP.NET Core.

Modify the JavaScript logic of the DateTimePicker Disabled Dates Demo with the code below:

function disableDates(date) {
    var currentDate = new Date();
    currentDate.setDate(currentDate.getDate() - 1);
    var endDate = new Date();
    var monthIndex = (new Date().getMonth() + 1) % 12;
    if (monthIndex == 0) {
        endDate.setYear(endDate.getFullYear() + 1);
    }
    endDate.setMonth(monthIndex);

    if (date && compareDates(date, currentDate, endDate)) {
        return false;
    } else {
        return true;
    }
}

function compareDates(date, startDateRange, endDateRange) {
    if (date.getTime() > startDateRange.getTime() && date.getTime() < endDateRange.getTime()) {
        return true;
    } else {
        return false;
    }
}

See the suggested behavior in action in this Telerik REPL example.

Notes

  • This solution uses JavaScript logic to disable the dates outside the specified range.
  • The code provided compares the selected date with the current date and the end date (current date + 30 days) to determine if it falls within the range.
  • You may need to adjust the logic to fit the specific restriction rules of the scenario at hand.

More ASP.NET Core DateTimePicker Resources

See Also

In this article