yerassyl
yerassyl

Reputation: 3057

How to query with comparison for current date in Parse

I am doing Parse + Android app. As parse automatically creates createdAt field of type Date for each object I want to construct a query where I compare current date.

This is something that I want to do:

ParseQuery<ParseObject> mealPlan = ParseQuery.getQuery("MealPlans");
mealPlan.whereEqualTo("created_at", current Date );

So basically I want to retrieve objects that were created today.

Upvotes: 1

Views: 2404

Answers (1)

kRiZ
kRiZ

Reputation: 2316

With whereEqualTo(), you're just querying objects created at exactly current Date. You should query the range of dates >= the 12:00am of today and < 12:00am of tomorrow (or <= 11:59pm of today if you want).

Use Parse's whereLessThan() and whereGreaterThanOrEqualTo().

// First, get the two dates (start and end of day)
// You'll find many algorithms to calculate these, 
// but here's a quick and easy one:

Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

// start of today
Date today = cal.getTime();

cal.add(Calendar.DAY_OF_MONTH, 1); // add one day to get start of tomorrow

// start of tomorrow
Date tomorrow = cal.getTime();

// Your query:
ParseQuery<ParseObject> mealPlan = ParseQuery.getQuery("MealPlans");
mealPlan.whereGreaterThanOrEqualTo("createdAt", today);
mealPlan.whereLessThan("createdAt", tomorrow);

NOTE:

The date calculation shown above is just a simple one, as the original question here is for the query and not calculating date. You will find many algorithms and libraries such as Joda-Time, which take into account the edge cases and daylight saving cases as well.

Upvotes: 3

Related Questions