Search code examples
javascriptjquerydatetimeflatpickr

How can I get selected full date in Flatpickr?


I can get the year and the day of the selected date but I can not get the month?

I want to get this date in my chosen date.

I want to get like this format "2018-01-27"

$("#date").flatpickr({
                    enableTime: false,
                    dateFormat: "Y-m-d",
                    inline: true,
                    minDate: result.results[i].start_date.split("T")[0],
                    maxDate: result.results[i].end_date.split("T")[0],

                    onChange: function(selectedDates, dateStr, instance) {
                        selectedDates.forEach(function (date){

                            console.log(date.getFullYear(), date.getDate(), date.getMonth());
                        })
                    }
                });

When I use date.getMonth() it returns 0

How can I get selected full date like this format "2018-01-27"


Solution

  • Months start from 0 in Javascript. January is 0, February is 1 and so on, December is 11. You will need to add 1 to the result of getMonth. Alternatively, you can define your own month getter to the Date prototype, like this:

    Date.prototype.getMyMonth = function() {return this.getMonth() + 1;};
    

    and test it like this:

    var foo = new Date();
    console.log(foo.getMyMonth);
    

    Just make sure that the function is defined before you use it.