luca
luca

Reputation: 37156

jquery datetime picker set minDate dynamic

I guys i'm using a datetimepicker by trentrichardson.com.

I have a form with two input fields : from and to and i want to be able to set dynamically a minDate to my "to" field equal to the value of my "from" field.

I know i should use a beforShow option but don't know how to implement the function.

$('.from,.to').datetimepicker({

    beforeShow: customRange

});

EDITED/SOLUTION

function customRange(input) {   
if (input.id == 'to') {     
var x=$('#from').datepicker("getDate");
$( ".to" ).datepicker( "option", "minDate",x ); 
} 
else if (input.id == 'from') {     
var x=$('#to').datepicker("getDate");
$( ".from" ).datepicker( "option", "maxDate",x ); 
} } 

Upvotes: 30

Views: 88760

Answers (10)

Waleed.alhasan
Waleed.alhasan

Reputation: 137

$('#fromDate').on('change', function () {
var fromDate = $('#fromDate').val();
//console.log(fromDate);
var parts = fromDate.split(' ');
var datePart = parts[0].split('/'); // YMD format
var timePart = parts[1].split(':');
console.log(datePart + '--' + timePart);

var newDate = new Date(datePart[0], Number(datePart[1]) - 1, datePart[2], timePart[0], timePart[1]);

var sMonth = (newDate.getMonth()) < 10 ? ('0' + (newDate.getMonth() + 1)) : (newDate.getMonth() + 1);
var sDay = (newDate.getDate()) < 10 ? ('0' + (newDate.getDate())) : newDate.getDate();
var sHour = (newDate.getHours()) < 10 ? ('0' + (newDate.getHours())) : newDate.getHours();
var sMinutes = (newDate.getMinutes()) < 10 ? ('0' + (newDate.getMinutes())) : newDate.getMinutes();

var endDt = newDate.getFullYear() + '/' + sMonth + '/' + sDay + ' ' + sHour + ':' + sMinutes;
//console.log(endDt);
console.log(newDate);
console.log(datePart[0] + '--' + (Number(datePart[1]) - 1) + '--' + datePart[2] + '--' + timePart[0] + '--' + timePart[1])

$('#toDate').val(endDt);
$('#toDate').datetimepicker({
    format: "Y/m/d H:i",
    useCurrent: false,
    minDate: (newDate.getFullYear() + '/' + sMonth + '/' + sDay),
    minTime: (sHour + ':' + sMinutes)
});

});

I set the minDate and MinTime using values extracted from the FromDateTime field, and worked. Note to set the datetimepicker to ToDateTime field just after changing and setting value in FromDateTime field

Upvotes: 0

manikandan
manikandan

Reputation: 815

Please use latest version of bootstrap.min.js

$("#from").datepicker( {
        format: "dd-mm-yyyy",
        endDate: '+0d',
        autoclose: true,
    }).on('changeDate', function(e) {
    
        var oldDate = $('.datepicker-current').val();
    
        $('#to').data('datepicker').setEndDate(oldDate);
    
    });

Upvotes: 2

Haritsinh Gohil
Haritsinh Gohil

Reputation: 6282

In jQuery UI datepicker there is many Functions which are helpful to set minDate or maxDate dynamically like onSelect, onClose.

demo of onClose is already provided in @Tanvir's answer see here: datepicker onClose example

So i will give you example of onSelect.

before it i will tell you difference between onSelect and onclose, as Name suggests onSelect fire just after user selects a date and onClose fire when datepicker closes after date selection, that's all.

here we have two datepicker pickupdate1 and pickupdate2, and we want to set selected date of pickupdate1 to be minDate of pickupdate2 and it should be dynamic, so here's the code:

$("#pickupdate1").datepicker({
    dateFormat: "dd-mm-yy",
    onSelect: function (selectedDate) {                                           
         $('#pickupdate2').datepicker('option', 'minDate', selectedDate);
    }
});
$("#pickupdate2").datepicker({
   dateFormat: "dd-mm-yy",
});

Upvotes: 1

Raghuram db
Raghuram db

Reputation: 1501

This worked for me

<input type="date" name="cname" value=""  min="<?php echo date("Y-m-d") ?>"/>

Upvotes: 0

Chris
Chris

Reputation: 997

None of the above answers helped me at all. It either didn't work or gave some kind of error.

So I merged them all together and made my own one. I used moment.js as mentioned above, just download it and include it in your page.

$("#start_date").datetimepicker({
    format: 'Y-m-d H:00:00',
    onChangeDateTime: function(dp, $input){
        var dt2 = $('#end_date');
        var minDate = $('#start_date').val();
        var currentDate = new Date();
        var targetDate = moment(minDate).toDate();
        var dateDifference = currentDate - targetDate;
        var minLimitDate = moment(dateDifference).format('YYYY/MM/DD');
        var endDate = moment(dt2.val()).toDate();
        if((currentDate - endDate) >= (currentDate - targetDate))
            dt2.datetimepicker({
                'value': minDate
            });
        dt2.datetimepicker({
            'minDate': '-'+minLimitDate
        });
    }
});
$("#end_date").datetimepicker({
    format: 'Y-m-d H:00:00'
});

I am sure there is a better way to do this but I couldn't find it. So I hope this helps someone in the future.

Upvotes: 1

Tanvir
Tanvir

Reputation: 1522

If you have two textboxes with corresponding IDs from and to and you want the minDate of to to be the selected date of from then do the following:

$("#from").datepicker({
    minDate: 0, // to disable past dates (skip if not needed)
    onClose: function(selectedDate) {
        // Set the minDate of 'to' as the selectedDate of 'from'
        $("#to").datepicker("option", "minDate", selectedDate);
    }
});

$("#to").datepicker();

Upvotes: 20

Matt McDonald
Matt McDonald

Reputation: 21

luca: A small addition to your answer...

Using the function you suggested the time component is ignored the first time the datetimepicker is displayed. If you close the datetimepicker and reopen it again, the time component mysteriously reappears. I'm not quite sure what is causing this, but it can be fixed with a bit of a hack:

function setMinMaxDate ( element )
{
    // Store current date - setting max/min date seems to destroy time component
    var val = $(element).val();

    if (element.id == 'endDate') 
    {     
        var x=$('#startDate').datetimepicker("getDate");
        $( element ).datetimepicker( "option", "minDate",x ); 
    } 
    else if (element.id == 'startDate') 
    {     
        var x=$('#endDate').datetimepicker("getDate");
        $( element ).datetimepicker( "option", "maxDate",x ); 
    }

    // Restore date
    $(element).val(val);
}

Upvotes: 2

uli78
uli78

Reputation: 1025

There is an example on trentrichardson.com. They are using "onSelect". For me it's not working perfert. When setting minDate or MaxDate the time component is set to 0 and only the date remains. And I had to solve some localization problems.

Upvotes: 0

andyb
andyb

Reputation: 43823

You can restrict the datepicker range.

But you want to set this range on creation of the datepicker on the "from". I made you a demo which seems to work OK as far as I understand the question.

Upvotes: 3

felixsigl
felixsigl

Reputation: 2920

you can set and get minDate dynamically with setter and getter:

//getter
var minDate = $( ".selector" ).datepicker( "option", "minDate" );
//setter
$( ".selector" ).datepicker( "option", "minDate", new Date(2007, 1 - 1, 1) );

explained here

Upvotes: 37

Related Questions