xdan / datetimepicker

jQuery Plugin Date and Time Picker
https://xdsoft.net/jqplugins/datetimepicker/
MIT License
3.5k stars 1.51k forks source link

Problem and potential solution: Date.parseDate is too picky with input text #305

Open vpstuart opened 9 years ago

vpstuart commented 9 years ago

Hi guys,

Loving the datepicker.

My users aren't too happy that when they enter a date in a format that is slightly different from that specified for the date picker, it is replaced with the current date/time.

I am currently implementing a workaround for a slightly fuzzier parsing function, and wanted to ask if it was worth putting back into the datetimepicker master:

This is the workaround:

(function() {
    var original = Date.parseDate;

    // http://xdsoft.net/jqplugins/datetimepicker/
    Date.parseDate = function( input, format ){
        var temp = original(input, format);
        if (temp !== null) {
            return temp;
        }

        temp = new Date(input);
        // http://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript
        if (!isNaN(temp.getTime())) {
            return temp;
        }

        return null;
    };
})();
lure commented 8 years ago

This is the answer. All possible format options MUST be specified. I am using date only here, so I have to provide both format and formatDate.

  jQuery(function() {
        var fmt = 'DD.MM.YYYY';
        Date.parseDate = function (input, format) {
            return moment(input, format).toDate();
        };
        Date.prototype.dateFormat = function (format) {
            return moment(this).format(format);
        };

        $.datetimepicker.setLocale("en");
        jQuery('#last-login-from').datetimepicker({
            format: fmt,
            formatDate: fmt,
            validateOnBlur: true,
            allowBlank: true,
            closeOnDateSelect: true,
            datepicker: true,
            timepicker: false,
            onShow: function (ct) {
                var endR = jQuery('#last-login-to').val();
                this.setOptions({
                    maxDate: endR ? endR : false
                })
            }
        });
        jQuery('#last-login-to').datetimepicker({
            format: fmt,
            formatDate: fmt,
            validateOnBlur: true,
            allowBlank: true,
            closeOnDateSelect: true,
            datepicker: true,
            timepicker: false,
            onShow: function (ct) {
                var stR = jQuery('#last-login-from').val();
                alert(stR);
                this.setOptions({
                    minDate: stR ? stR : false
                })
            }
        });
    });