Fahad
Fahad

Reputation: 99

Time Selector should not let me select time more than now

I have 2 textboxes. One for Date and one for time. enter image description here. I can set maxDate: new Date but that will ake it for every date I pick up from the calendar. I also tried

$('#datetimepickerExample').datetimepicker({
                format: 'LT', stepping: 1, autoclose: true,
                onClose: function (selectedDate) {
                    $("#ContentPlaceHolder1_Event_Date_Txt").datepicker("option", "maxDate", selectedDate);
                }
            });

where "ContentPlaceHolder1_Event_Date_Txt" is the Date Textbox but it doesn't work. So when I pick an earlier date I can select all the 24 hours but when I select today it should limit me to the current time.

Upvotes: 1

Views: 1095

Answers (2)

Dimitar
Dimitar

Reputation: 1180

Here is a relatively simple function that solves this:

const isInThePast = date => {
    const now = new Date()
    if (typeof date !== typeof now) return "Invalid Date"
    else return date < now ? true : false
}

You can call this function on every date change event and if it returns true, set the value, if it returns false give the user some sort of warning and keep the previous value.

Upvotes: 0

Ravenwits
Ravenwits

Reputation: 68

Before trying the method I've written below, I encourage you to read the plugin documentation here. I did not read whole documentation but I wanted to point out at least a direction for you.

1 - You should get current system date and time.

You can achieve that with JavaScript GetDate() Method

function getNow() { 
    var e = new Date, 
    month = e.getMonth() + 1, 
    date = e.getDate(), 
    year = e.getFullYear(); 
    month < 10 && (month = "0" + month.toString()), date < 10 && (date = "0" + date.toString()); 
    var currentTime = e.getHours() + ":" + e.getMinutes();
    var currentDate = month + "/" +  date + "/" + year; 

    //currentDate
    //03/27/2021   

    //currentTime
    //11:20
}

2 - If current date equals to the date you've picked you should limit the max time input to the current time. I believe you can achieve that with the code below. As I've said I did not read the documentation for the plugin you are using.

$("#ContentPlaceHolder1_Event_Date_Txt").datepicker({
    onSelectDate:function(currentTime){
      $('#datetimepickerExample').datetimepicker("option", "maxTime", currentTime);
    }
});

Good Luck!

Upvotes: 1

Related Questions