Search code examples
jqueryhtmldatepickerflatpickr

How to get the date input from flatpickr?


I am changing my jquery ui datepicker to flatpickr. But i need to know how i can do this $('#from2').datepicker('getDate') for flatpickr. I cant find it online how to do it with flatpickr.

Thanks for your time.

*EDIT

function getDays() {
    let start = $('#from1').datepicker('getDate'),
        end   = $('#to1').datepicker('getDate'),
        days  = (end - start) / 1000 / 60 / 60 / 24;
        if(days == 0 || days > 0) {
    $('#howManyNights').val(days);
  }
    return days;
}

*Doesnt work with flatpickr:

function getDays() {
    let start = $('#from1').val();
        end   = $('#to1').val();
        days  = (end - start) / 1000 / 60 / 60 / 24;
        console.log(days);
        if(days == 0 || days > 0) {
    $('#howManyNights').val(days);
    }
    return days;
}

days = Nan


Solution

  • Try it like this, by making date objects out of the values of the flatpickr (working snippet that you can run)

    var from1 = flatpickr('#from1', {});
    var to1 = flatpickr('#to1', {});
    
    function getDays() {
        var start = new Date($('#from1').val());
        var end   = new Date($('#to1').val());
        days  = (end - start) / 1000 / 60 / 60 / 24;
        if(days == 0 || days > 0) {
          $('#howManyNights').val(days);
        }
        return days;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.3/flatpickr.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.3/flatpickr.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    
    From:<input name="from1" id="from1" type="text">
    To:<input name="to1" id="to1" type="text">
    How Many:<input name="howManyNights" id="howManyNights" type="text">
    <button onclick="getDays()">Get Days</button>