0

我有字符串格式的开始日期和结束日期。我想比较结束日期​​和开始日期,结束日期应该大于开始日期。如何做到这一点。

NSLog(@"%@",date);
NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"dd MM yyyy"];

_start_date = [[NSDate alloc] init];

_start_date = [df dateFromString: date];

NSLog(@"date: %@", _start_date);`

开始日期为零。

4

2 回答 2

0

创建 NSDateFormatter 的实例。配置它。解析字符串以获取 NSDate 对象 (dateFromString:)。比较它们(比较:)。

于 2014-03-13T07:20:24.337 回答
0

您需要使用NSDateFormatterNSDate将两个字符串都转换为对象。

由于您的日期是dd-MM-yy格式,请执行以下操作:

NSString *dateStr1 = @"21-3-14";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"dd-MM-yy"];
NSDate *date1 = [dateFormatter dateFromString:dateStr1];

同样创建另一个日期,比如说date2然后你可以比较这些日期。

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");        

} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");

} else {
    NSLog(@"dates are the same");
}
于 2014-03-13T07:20:43.837 回答