SRMR
SRMR

Reputation: 3134

Query Parse for dates greater than Today

I'm trying to query my Parse database for all the dates greater than today's date.

I will then list those items in a table.

I can't quite get it to work, and also am unsure what format to put the dates in my Parse database as.

This is what I've tried:

// Date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterFullStyle];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
NSLog(@"Date Today: %@", dateToday);

// Initialize table data
PFQuery *query = [self queryForTable];
[query whereKey:@"dateTime" greaterThan:dateToday];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

Parse database:

enter image description here

Any ideas for what I'm missing or need to add?

Upvotes: 0

Views: 3020

Answers (2)

ardrian
ardrian

Reputation: 1249

The problem with your above code is that you are storing your date as a String object, rather than a Date object. This is useless for the comparison query you wish to do.

When using the iOS Parse library, you can pass an NSDate object into a PFQuery.

NSDate* now_gmt = [NSDate date]; 

PFQuery *query = [self queryForTable];
[query whereKey:@"dateTime" greaterThan:now_gmt];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

You'll want to make sure all your queries and dates are stored in GMT time, which is an exercise left to the reader.

Saving date as object field

This should be pretty obvious, but saving to save a date in the first place you would do something like:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:14];
[comps setMonth:2];
[comps setYear:2015];
NSDate* myDate = [[NSCalendar currentCalendar] dateFromComponents:comps];

PFObject *testObject = [PFObject objectWithClassName:@"TestObject"];
testObject[@"test"] = @"Test 1";
testObject[@"testDate"] = myDate;
[testObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

Upvotes: 2

peterho
peterho

Reputation: 74

For me, I do not use different date formats storing in database. I put double value in the database. It is easy for comparison.

        double d_dateTime = [[NSDate date] timeIntervalSince1970];

Upvotes: 1

Related Questions