1

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.

kRiZ
  • 2,320
  • 4
  • 28
  • 39
yerassyl
  • 2,958
  • 6
  • 42
  • 68
  • I think you want createdAt dates that are > yesterday and < tomorrow. Here's a good article on building those dates http://stackoverflow.com/questions/6850874/how-to-create-a-java-date-object-of-midnight-today-and-midnight-tomorrow – danh Jan 19 '16 at 17:38

1 Answers1

3

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.

kRiZ
  • 2,320
  • 4
  • 28
  • 39