iOS NSDateFormatter Date为零之后

时间:2014-05-24 19:11:56

标签: ios objective-c nsdateformatter null

我的日期格式化程序有问题。我想比较两个日期,但在我得到两个相同格式后,日期为零。

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");
}

1 个答案:

答案 0 :(得分:1)

使用dateFormat字符串@"yyyy-MM-dd HH:mm:ss Z"代替。您的dateFormat与您尝试转换的字符串格式不符。

顺便说一下,将[NSDate date]转换为字符串然后再转回是没有意义的。只需使用[NSDate date]并完成它:

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

[device valueForKey:@"finishDate"]可能也是如此。如果那已经是NSDate对象,只需使用它并完全绕过格式化程序。