简体   繁体   中英

How do I to get the canonicalized min/max values in jQuery UI's datepicker's beforeShow method?

I have a pair of datepicker objects that I would like to act as a range, so that setting a value in the "low" one adjusts the minDate (and yearRange) in the other and similarly with the "maxDate" in the other one. The problem is the type of what I get seems like it can be a date or a string or a number or ??? so I am having trouble using it to set the other values. Code snippet below:

$(document).ready(function() {
$( '#from' ).datepicker({          /* the "low" datepicker */
    showOn:         'button',
    changeMonth:        true,
    changeYear:     true,
    defaultDate:        null,
    minDate:        new Date(2009,0,1),
    maxDate:        null,
    buttonImageOnly:    true,
    buttonImage:        '/img/calendar_icon_20x20.png',
    buttonText:     'select date from calendar',
    dateFormat:     'dd-M-yy',
    beforeShow:
        function ( inp, inst ) {
            var v;
            var o = {};
            var miny = new Date(inst.settings.minDate).getFullYear();
            var maxy = new Date(inst.settings.maxDate).getFullYear();

            v = $( '#thru' ).val();  /* the "high" datepicker */
            if (v == '') {
                v = $( '#thru' ).datepicker('option', 'maxDate');
            }
            if (typeof v == 'object') {
                o.maxDate = v;
            } else {
                o.maxDate = $.datepicker.parseDate('dd-M-yy', v.trim());
            }
            maxy = o.maxDate.getFullYear();
            o.yearRange = miny + ':' + maxy;
            return o;
        }
    });
});

And I figure I'm going to need to add an if (typeof v == 'number') {..} section and try to compute a date from a numerical days offset, and then I still have to worry that if I get a string that it doesn't match up with the dateFormat so the parse will fail. I assume that there is something in the datepicker code which is already having to do this canonicalization of inputs for default/min/maxDate (presumably into a Date object) isn't there some way for me to access the already canonicalized value (rather than reinventing the wheel badly as I've been doing thus far)?

Well, I grabbed the un-minified jquery-ui source and scrounged through it and as near as I can tell it doesn't seem to keep the canonicalized dates any place, it recomputes them each time it needs them. It seems there is a "private" function, _determineDate , which you can access to do this canonicalizing, but that's obviously not very future-proof. Anyway for completeness, here it is:

var rawvalue = $( '#other' ).datepicker('option', 'minDate');
var asDate = $.datepicker._determineDate(inst, rawvalue, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM