Sumomo
Sumomo

Reputation: 623

How to best access a day property from a selected date in flatpickr?

My mission is for the user to select a date (it is displayed as normal in the input box). A new variable is created that contains the year, BUT using some logic from the date supplied to alter it if necessary.

I don't know if I am meant to just work with the supplied .selectedDates date array, or if flatpickr can give me back a date in a format that includes the day as a separate property?

(The logic will be if you were born between the 1st January and the 3rd February, you will fall into the previous calendar year, it's for an Asian spiritual system)

So far I have this:

const fp = flatpickr("#demo", {
  onChange: [
    function () {
      printDate (fp.selectedDates);
      printDate (fp.currentYear);

    }
  ],
});

function printDate(date) {
  console.log(date);
}

I can't seem to get at the Day as a variable using flatpickr methods or object properties? There is no day property, but there is year and month.

I can use fp.currentYear but there is no currentDay. What is the solution? Thanks!

Upvotes: 0

Views: 2475

Answers (1)

yuriy636
yuriy636

Reputation: 11681

currentYear and currentMonth refer to the displaying year and month, not selected ones.

You are meant to work with selectedDates, which is an array of native JavaScript Date objects.

Once got the array, you can get the day by using .getDate(). (For other properties check MDN Date docs).

var inputDate = flatpickr(".flatpickr", {
  onChange(selectedDates) {
    console.log(selectedDates);
    console.log("Selected day:" + selectedDates[0].getDate());
  }
});
<link rel="stylesheet" href="https://unpkg.com/flatpickr/dist/flatpickr.min.css">
<script src="https://unpkg.com/flatpickr"></script>

<input class="flatpickr" type="text" placeholder="Select Date.." readonly="readonly">

Upvotes: 2

Related Questions