react-native-calendars日期偏移1天:周五30日显示为周六问题求助
Hey there! That date offset issue is super common with react-native-calendars—it almost always boils down to timezone handling or how you're formatting your date values. Let's walk through the most likely fixes:
1. Ensure Your Dates Are Formatted Correctly (No Timezone Baggage)
The component expects date strings in a strict YYYY-MM-DD format without timezone information. If you're generating dates with new Date() directly, you might be accidentally including timezone offsets that throw off the calendar's parsing.
Try creating a helper function to format your dates properly:
const formatToCalendarDate = (date) => { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed! const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; }; // Use this helper for minDate, maxDate, and markedDates const minDate = formatToCalendarDate(new Date()); const maxDate = formatToCalendarDate(new Date(Date.now() + 30 * 24 * 60 * 60 * 1000));
2. Verify Your markedDates Structure
Double-check that the keys in your markedDates object are also in the YYYY-MM-DD format. Avoid using Date objects or strings with timestamps/timezones here—stick to plain date strings:
// Correct format this.setState({ markedDates: { '2024-05-30': { selected: true, marked: true } } }); // Avoid this (includes timezone data that can cause offsets) // '2024-05-30T00:00:00.000Z'
3. Manually Set the Timezone Offset (If Needed)
If formatting dates doesn't fix it, you can explicitly set the timezoneOffset prop to match your local timezone. This prop accepts the number of minutes your timezone is offset from UTC (positive for east, negative for west).
You can auto-calculate it using the native Date object:
<Calendar style={{width: Dimensions.get('screen').width - 10}} theme={{ selectedDayBackgroundColor: '#00adf5', selectedDayTextColor: '#ffffff', dotColor: '#00adf5', }} onDayPress={this.onDaySelect} markedDates={this.state.markedDates} markingType="single" minDate={minDate} maxDate={maxDate} disableAllTouchEventsForDisabledDays={true} timezoneOffset={new Date().getTimezoneOffset() * -1} // Auto-adjust to local timezone />
Why This Happens
react-native-calendars internally parses dates using UTC by default. If your date values include local timezone information (e.g., a Date object created in your local time), the component might convert it to UTC and then display it back in your local timezone—resulting in a 1-day shift depending on the time of day.
Start with step 1 (proper date formatting) first—it's the most reliable fix for this issue.
内容的提问来源于stack exchange,提问作者Maksim Parkhomenko

