Disable Past date time in DateTimePicker jQuery plugin

Nowadays i was working a project and in this project one of the task i am using DateTimePicker jQuery plugin to select date time. According the task requirement I don’t want to allow user to select any past date time, only user can select current or future date time. So Today in this article i will explain how to Disable Past date time with DateTimePicker jQuery plugin.

Read Also: How to Install DateTimePicker jQuery plugin

Disable Past date time in DateTimePicker jQuery plugin

First we try to disable Past Date with minDate: 0 option:

//minDate option Example
$('#datetimepicker5').datetimepicker({
	minDate:0, // disable past date
});

Output:

Now i try to disable Past Date and Time with minDate: 0 and minTime: 0 option:

//minDate and minTime option Example
$('#datetimepicker6').datetimepicker({
	minDate: 0,  // disable past date
	minTime: 0, // disable past time
});

Output:

In the above output i have found two issue:

Issue 1: If current time is 2:00 AM, then user can’t select current time to 2:00 AM.

Issue 2: If user select future date then some time disable, e.g if current time is 3:00 AM, user can’t select time to 3:00 AM, 2:00 AM, 1:00 AM. But i want if user select future date then every time should be visible to select.

so here minTime: 0 option did’t work for me.

I wrote below code to fix above issues, in this code if user select today date then pass current time with minTime option and for future date all time will be visible to select.

var checkPastTime = function(currentDateTime) {

var d = new Date();
var todayDate = d.getDate();

// 'this' is jquery object datetimepicker
if (currentDateTime.getDate() == todayDate) {
	this.setOptions({
		minTime: d.getHours() + ':00' //here pass current time hour
	});
} else
	this.setOptions({
		minTime: false
	});
};

$('#datetimepicker7').datetimepicker({
	format:'Y-m-d H:i',
	minDate : 0,
	onChangeDateTime:checkPastTime,
	onShow:checkPastTime
});

I can’t express how happy I am to see my code is working fine.

2 Comments
  1. Oliver Schade says

    Hi,

    nice function btw.

    But I have a the opposit of your problem with the future. :).
    If the user change the day to a past day, the time is selectable.
    So the user can select a disabled date via the time slot.

    Regards,
    Oliver

    1. Full Stack developer says

      Hello Oliver Schade,

      Thanks for your reply and highlights this point But when i was working this point that time my project requirement admin can not choose past date time while set lead emails.

Leave A Reply

Your email address will not be published.