Home » Android » How to query android calendar events for specific date range?

How to query android calendar events for specific date range?

Posted by: admin June 16, 2020 Leave a comment


I am querying events table in android to get events.

String[] projection = new String[] { "calendar_id", "title", "description",
                    "dtstart", "dtend", "eventLocation" };

Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/events"),

This returns all the events. But now I want events only in specific duration say 4/03/2013 to 7/03/2013. How do I use selection and selectionArgs[] ?
I tried this

String selection = "((dtstart <= ?) AND (dtend >= ?))";
String[] selectionArgs = new String[] {startString, endString};

But its not returning anything. My doubt are
1. Will where clause work ? Because, startDate and endDate are first converted to long (milliseconds) and then to String and then are stored in the table. So how can strings be compared for their long values. There is no toNumber() function in sqlite.
2. If I’m passing selectionArgs then startString and endString should be in which format ?

How to&Answers:

startString & endString should be passed in millis. Try using:

Calendar c_start= Calendar.getInstance();
c_start.set(2013,2,4,0,0); //Note that months start from 0 (January)   
Calendar c_end= Calendar.getInstance();
c_end.set(2013,2,7,0,0); //Note that months start from 0 (January)

Also, I think your logic is reversed, date range should be like this:

String selection = "((dtstart >= "+c_start.getTimeInMillis()+") AND (dtend <= "+c_end.getTimeInMillis()+"))";