2011-06-11 35 views
0

可能重复:
Comparing dates
How to compare two dates in Objective-C如何在Objective-C两个字符串比较

我想比较两个字符串谁有一个日期格式“2011年11月6日例如“和”12-06-2011“为例。 我想看看第二个日期是否大于第一个或不是 你能帮助我吗?


我想这码

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"dd-MM-YYYY"]; 
    NSDate *date1 = [dateFormat dateFromString:deparatureDateField.text]; 
    NSDate *date2 = [dateFormat dateFromString:comebackDateField.text]; 
    [dateFormat release]; 
    NSTimeInterval timeInterval = [date1 timeIntervalSinceDate:date2]; 
    if(timeInterval >= 0) 
    { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Attention" message:@"come back date should be greater" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil]; 
     [alert show]; 
    } 

但我ALWAYSE有一个警报,NSTimeInterval一个时间间隔是ALWAYSE NULL

回答

5

要了解一个日期比其他的你不得不大做到这一点:

NSString *string1 = @"11-06-2011"; 
NSString *string2 = @"12-06-2011"; 

// Convert string to date object 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"dd-MM-yyyy"]; 
NSDate *date1 = [dateFormat dateFromString:string1]; 
NSDate *date2 = [dateFormat dateFromString:string2]; 
[dateFormat release]; 

NSComparisonResult comparisonResult = [date1 compare:date2]; 

/* 
NSComparisonResult can be either of these values: 
- NSOrderedAscending (-1) //if date1 < date2 
- NSOrderedSame (0)  //if date1 = date2 
- NSOrderedDescending (1) //if date1 > date2 
*/ 

或者(compare:),你可以使用timeIntervalSinceDate:得到实际时差:

NSTimeInterval timeInterval = [date1 timeIntervalSinceDate:date2]; 
//timeInterval will be 
// - nagative if ascending, 
// - zero if same, 
// - positive if descending 
+0

@Regexident @murat thakyou但我想我的问题不清楚。我不想看看是否有平等的,我想看看第二个日期是否大于第一个日期 – user794317 2011-06-11 22:36:19

+0

@ user794317:更新了我的答案。看第二个片段。 – Regexident 2011-06-11 22:44:49

+0

@Regexident非常感谢你,但我总是有麻烦,我更新了我的问题 – user794317 2011-06-11 23:33:22

1

其实它取决于你比较后会做什么。如果你想保持最新信息作为一个字符串和比较字符串是

[@"11-06-2011" isEqualToString: @"12-06-2011"] 

足够你

0

看看NSDates timeIntervalSinceNow,你可以从两个日期比较的时间间隔,看看哪一个是最近等

NSTimeInterval *interval = [someDate timeIntervalSinceNow]; 
+1

为什么要循环的方式,如果有[[date1 timeIntervalSinceDate:date2]';) – Regexident 2011-06-11 22:53:44