CalendarView调用setMinDate()与setMaxDate()出现日期设置异常问题
Let’s break down what’s going on here and walk through a verified fix for the issue.
First, let’s confirm the timestamp values you’re working with:
1517164200000translates to 29-01-2018 09:30:00 (UTC+8) (or 01:30 UTC)1517682600000translates to 04-02-2018 09:30:00 (UTC+8) (or 01:30 UTC)
The Root Cause
The problem almost certainly ties to timezone ambiguity and how CalendarView parses raw timestamps. When you pass a timestamp that’s not aligned to the start/end of a day, some Android versions (especially older ones) can misinterpret the date due to UTC-local timezone shifts. In your case, it’s likely that the partial-day timestamp is triggering a bug where CalendarView falls back to the last day of the target month instead of respecting the exact date.
Verified Fix: Explicitly Set Dates with Calendar Class
Instead of using raw timestamps, use the Calendar class to build your start/end dates with clear timezone alignment. This eliminates any parsing ambiguity and ensures CalendarView interprets the dates correctly.
Here’s the corrected code:
// Set start date: 29-01-2018 (start of day) Calendar startCalendar = Calendar.getInstance(); startCalendar.set(2018, Calendar.JANUARY, 29, 0, 0, 0); startCalendar.set(Calendar.MILLISECOND, 0); long startDateTimeMillis = startCalendar.getTimeInMillis(); // Set end date: 04-02-2018 (end of day) Calendar endCalendar = Calendar.getInstance(); endCalendar.set(2018, Calendar.FEBRUARY, 4, 23, 59, 59); endCalendar.set(Calendar.MILLISECOND, 999); long endDateTimeMillis = endCalendar.getTimeInMillis(); // Apply to CalendarView calendarView.setMinDate(startDateTimeMillis); calendarView.setMaxDate(endDateTimeMillis);
Why This Works
Calendar.getInstance()uses your device’s local timezone, matching howCalendarViewdisplays dates to the user.- Setting the start date to midnight (00:00:00.000) ensures
CalendarViewrecognizes the full start date as allowed. - Setting the end date to the last millisecond of 04-02-2018 guarantees the entire day is included in the allowed range, bypassing any edge-case parsing bugs that might push the max date to the month’s end.
Testing Your Original Code
When we plug your original timestamp into a Calendar instance, it correctly shows 04-02-2018—so the timestamp itself is valid. The issue is purely in how CalendarView processes non-aligned timestamps. Using the Calendar class to construct your dates is the most reliable way to avoid this kind of unexpected behavior.
内容的提问来源于stack exchange,提问作者Rumit Patel

