-4

i have a problem with the Date Formatter. I Want to compare Two dates, but after i get both of the to the same format, the date is nil.

compareDateNowString = 2014-05-24 19:03:39 +0000
compareDateFininshString = 2014-05-24 18:30:24 +0000 

    NSDateFormatter *compareFormatter = [[NSDateFormatter alloc]init ];
[compareFormatter setDateFormat:@"dd-MM-yyyy HH.mm"];

NSString *compareDateNowString = [NSString stringWithFormat:@"%@", [NSDate date]];
NSDate *compareDateNow = [compareFormatter dateFromString:compareDateNowString];
NSString *compareDateFinishString = [NSString stringWithFormat:@"%@", [device valueForKey:@"finishDate"]];
NSDate *compareDateFinish = [compareFormatter dateFromString:compareDateFinishString];

NSComparisonResult result = [compareDateNow compare:compareDateFinish];

if(result==NSOrderedAscending)
{
    cell.backgroundColor = [UIColor colorWithRed:0.0 green:255.0 blue:0.0 alpha:0.5];
}
else if(result==NSOrderedDescending)
{
    cell.backgroundColor = [UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.5];
}
else
{
        NSLog(@"Both dates are the same");
}
JaWeilBaum
  • 67
  • 1
  • 1
  • 4

1 Answers1

2

Use a dateFormat string of @"yyyy-MM-dd HH:mm:ss Z" instead. Your dateFormat does not match the format of the string you're trying to convert.

By the way, there's no point in converting [NSDate date] to a string and back again. Just use [NSDate date] and be done with it:

NSDate *compareDateNow = [NSDate date];
NSComparisonResult result = [compareDateNow compare:compareDateFinish];

The same might be true for [device valueForKey:@"finishDate"]. If that's already a NSDate object, just use that and bypass the formatter entirely.

Rob
  • 415,655
  • 72
  • 787
  • 1,044