uxsolutions / bootstrap-datepicker

A datepicker for twitter bootstrap (@twbs)
Apache License 2.0
12.66k stars 6.07k forks source link

Allow for lazy date input in "d.m.yy" format when desired format is "dd.mm.yyyy" #713

Closed Boerney closed 8 years ago

Boerney commented 10 years ago

I have set up datepicker with german locale so dates are expected in "dd.mm.yyyy" format. However, many users are lazy and key in dates without leading zeros. It was very annoying that datepicker doesn't accept such values. E.g., you type in "3.5.2014", which shoud be May 3rd, 2014 (and which I think is totally unambiguous), but datepicker wouldn't accept the date.

I'm not very good at JS, but I searched bootstrap-datepicker.js for what I thought was the problem and I have made a litte addition that I think might be of use to others as well. In fact, I post it here in hope for comments whether this is a good idea or why it should or should not work - it seems to work so far.

I found a part that starts with

parseDate: function(date, format, language)

After the line "if (date instanceof Date) return date;" I added this:

var my_str = date.split("."); if ( Number(parseInt(my_str[0], 10)) && Number(parseInt(my_str[1], 10)) && Number(parseInt(my_str[2], 10)) ) { date = ("0" + my_str[0]).slice(-2)

So I check whether it is numbers divided by dots, and if so, I make sure that numbers have a leading zero and that the year is four-digit. Only after that the standard "parseDate" routine is executed.

It actually seems to work much better than I hoped. As soon as the input field has something that matches "numbers divided by dots", the datepicker panel even marks the right date in the calendar.

Note that my simple implementation only works for years 2010+, as I only prepend "20" (with 2005, I should prepend "200", I guess). It's also not a good solution if a two-digit year is ambiguous - but if all dates are in the future and "13" can only be 2013 (vs. 1913), I guess it's safe.

I'd really like comments on this as I don't feel too comfortable to just manipulate code I don't fully understand. I'm totally new to GitHub and apologise if this doesn't belong here.

(I hope that) I attached a screenshot that shows the result. Left is the demo page, with German locale, and the result when you key in "3.5.14". (Actually, I've never seen that "NaN" errors on my own page??? Datepicker just doesn't pick up the right date and replaces it by today's date, but it doesn't give "NaN".) Right is the result after my addition to the code. When the input loses focus, the date is even displayed in "dd.mm.yyyy" format. So I'm very happy with the result... but:

I hope the whole thing doesn't have any undesired side effects!

bild1

Azaret commented 8 years ago

Hi, sorry for the late reply. Is this still an issue for you ? I do believe this have been fixed in the latest release.

hebbet commented 8 years ago

closing, feel free to reopen.