Joe Scotto
Joe Scotto

Reputation: 10887

Flatpickr and Moment.js unexpected date format

I'm using the following instantiation code for Flatpickr.

$("#entry_date_time").flatpickr({
    enableTime: true,
    altInput: true,
    defaultDate: moment().format("YYYY-MM-DD HH:MM:SS"),
    dateFormat: "YYYY-MM-DD HH:MM:SS",
    minuteIncrement: 1
});

The issue I'm having is that moment().format("YYYY-MM-DD HH:MM:SS"); gives me the right data but the output of $("#entry_date_time").val() is equal to

2017201720172017-JanJan-SatSat 0000:JanJan:0000

instead of the expected format I provided.

Any ideas as to what could be causing this would be great, thanks for any help!

Upvotes: 3

Views: 8649

Answers (2)

Abdul Rauf
Abdul Rauf

Reputation: 6221

Flatpickr has its own formating tokens that are different from the ones supported by moment. But the good thing is you can use parseDate and formatDate config options to support custom formatting tokens.

/* A custom datestring parser */
parseDate: (date: string, format: string) => Date;

/* Allows using a custom date formatting function instead of the built-in. Generally unnecessary.  */
formatDate: (date: Date, format: string, locale: Locale) => string;

Example with moment.js compatible tokens https://jsfiddle.net/armujahid/pwqhznj0/

const fp = flatpickr(".date", {
  altInput: true,
  dateFormat: "YYYY-MM-DD",
  altFormat: "DD-MM-YYYY",
  allowInput: true,
  parseDate: (datestr, format) => {
    return moment(datestr, format, true).toDate();
  },
  formatDate: (date, format, locale) => {
    // locale can also be used
    return moment(date).format(format);
  }
});

Reference: my comment at https://github.com/flatpickr/flatpickr/issues/1549#issuecomment-537939826

Update: this snippet has also been added in official docs

Upvotes: 6

Paul T.
Paul T.

Reputation: 4942

Based on the output, and looking at the flatpickr docs for date and time, it seems that only single characters are expected in the format instead of multiple ? For example, the 4 Y's would explain the year being repeated 4 times, the month twice, etc.

The dateFormat that you need should probably be:

dateFormat: "Y-M-D H:i"

...however, I do NOT see a formatting option for the seconds portion of the time by flatpickr?

Update on the seconds:

There is a flatpickr feature request for the seconds capability.

Upvotes: 2

Related Questions