DatePickerDialog incorrectly enforcing a minimum date of Jan 1, 1970

前端 未结 4 1720
星月不相逢
星月不相逢 2021-01-04 20:30

We have a member reporting that he is unable to set a date before Jan 1, 1970 on our DatePickerDialog. This issue does not repro for us.

I am already aware that the

4条回答
  •  悲&欢浪女
    2021-01-04 21:25

    I realize this question is a little old, and that this answer will not apply to older devices, but I've recently been made aware of this issue on a newer device (the Huawei Mediapad 7 Youth), so I figured I'd update this with newer information:

    Starting with API 11, the methods necessary to do this are exposed. Remember, while Calendar may use Unix Epoch as zero, Java (at least until ~JRE 8?) uses signed numbers, so negatives are completely acceptable. Thankfully you don't need to be fully aware of this, as this code runs fine:

    // This is API 11!
    try {
        // Hack to (try to) force minDate to 1888 instead of 1970.
        DatePicker dp = dialog.getDatePicker();
        Calendar minCal = Calendar.getInstance();
        minCal.set(1888, Calendar.JANUARY, 1, 0, 0, 0);
        dp.setMinDate(minCal.getTimeInMillis());
    
        if (maxDate > 0)
            dp.setMaxDate(maxDate);
    } catch (NoSuchMethodError e) {
        Log.w(TAG, "Can't set min/max dates: device/Android version is too old.");
    }
    

    I used 1888 so that any reports stating this is the minimum will make it clear that the code was executed and not ignored/overridden. I should note I have not yet heard back whether or not this works on the reported device.

提交回复
热议问题