Android Calendar All Day event dates are off by one day for GMT +x Areas

前端 未结 3 592
小蘑菇
小蘑菇 2020-12-28 18:25

I wrote a simple code to insert an all day event into the calendar, using the tutorial from the official site. http://developer.android.com/guide/topics/providers/calendar-p

3条回答
  •  无人及你
    2020-12-28 19:23

    The docs for CalendarContract.EventsColumns state "If allDay is set to 1 eventTimezone must be TIMEZONE_UTC and the time must correspond to a midnight boundary."

    My solution to ensure that expected dates would be returned after querying the API was to a)Set the start and end event values with dates aligned to UTC. b)Adjust the time returned after querying to take the device timezone and DST into account.

    a)

    @Before
    public void setup(){
        ...
        mJavaCalendar = Calendar.getInstance();
        mInputStart = getUtcDate(
                mJavaCalendar.get(Calendar.YEAR),
                mJavaCalendar.get(Calendar.MONTH),
                mJavaCalendar.get(Calendar.DAY_OF_MONTH));
    }
    
    private long getUtcDate(int year, int month, int day){
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        calendar.set(year, month, day,0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }
    
    @Test
    public void jCalAlldayTzDflt0000To2400(){
        mTodayEvent.setEventStart(mInputStart);
        mTodayEvent.setEventEnd(mTodayEvent.getEventStart() +  DateUtils.DAY_IN_MILLIS);
        mTodayEvent.setAllDay(true);
        ...
    }
    

    b)

    public static long getTzAdjustedDate(long date){
        TimeZone tzDefault = TimeZone.getDefault();
        return date - tzDefault.getOffset(date);
    }
    
    public void getCorrectDate(cursor){
        isAllDay() == 1 ? DateTimeUtils.getTzAdjustedDate(cursor.getLong(INST_PROJECTION_BEGIN_INDEX)) :
                cursor.getLong(INST_PROJECTION_BEGIN_INDEX));
    

    I hope this helps.

提交回复
热议问题