chrisdavies / tiny-date-picker

A small, modern, dependency-free date picker
https://chrisdavies.github.io/tiny-date-picker/
415 stars 87 forks source link

onOpen after format #44

Closed matteocollina closed 7 years ago

matteocollina commented 7 years ago

I used : format: function (date) { return date.toLocaleDateString(); }

and, for example i have 3/7/2017 (3rd of July 2017) but when i open the calendar , i found 7/3/2017 (7th of March 2017)

chrisdavies commented 7 years ago

Oh. That's no good. I'll have a look at this tomorrow. Sorry, I'm a bit behind on replies here.

yunusbayraktaroglu commented 7 years ago

Hi Chris, thank you for your cool lightweight script.

I have same problem. When i change the format(Js line 81) and select a day, calender is selecting 'Today' on reopen.

chrisdavies commented 7 years ago

Ah. Sorry it took me so long to dig into this. If you specify format you also need to specify parse which is responsible for converting from your format back into a proper date.

Here's an example, using an obviously custom format which the JS date object won't know how to parse:

            format (dt) {
              return dt.getFullYear() + '|' + dt.getMonth() + '|' + dt.getDate();
            },
            parse (dt) {
              if (!dt) {
                return new Date();
              }

              const [year, month, day] = dt.split('|').map((s) => parseInt(s, 10));
              const result = new Date();
              result.setYear(year);
              result.setMonth(month);
              result.setDate(day);
              return result;
            }

Note, the if (!dt) { clause is important, because the date string is initially undefined.