2015-10-07 16 views
0
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init]; 

[timeFormatter setDateStyle:NSDateFormatterNoStyle]; 

[timeFormatter setTimeZone:[NSTimeZone localTimeZone]]; 

[timeFormatter setDateFormat:@"dd/MM/YYYY HH:mm"]; 

NSDate *startDate = [timeFormatter1 dateFromString:@"07/10/2015 12:30"]; 

NSDate *EndDate = [timeFormatter1 dateFromString:@"08/10/2015 02:30"]; 


if([startDate compare:EndDate] == NSOrderedAscending) 

    return YES; 

else 

    return NO; 

我跟隨上面的代碼,但每次輸出都是錯誤的結果(去「返回否」)。如何比較兩個日期和時間,EXP:07/10/2015 12:30至08/10/2015 02:00在ios中?

同時EXP:07/10/2015 12:30到07/10/2015 23:30這是工作。

我需要在一個時間兩種格式的工作。

請幫幫我嗎?

+0

我認爲你錯了'timeFormatter1'。可能你錯過了'timeFormatter'。並且在startDate和EndDate中爲零。 –

回答

0

的問題是在一年的格式。使用「yyyy」代替「YYYY」來解決問題。

這裏的工作代碼:

NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init]; 

    [timeFormatter setDateStyle:NSDateFormatterNoStyle]; 

    [timeFormatter setTimeZone:[NSTimeZone localTimeZone]]; 

    [timeFormatter setDateFormat:@"dd/MM/yyyy HH:mm"]; 

    NSDate *startDate = [timeFormatter dateFromString:@"07/10/2015 12:30"]; 

    NSDate *EndDate = [timeFormatter dateFromString:@"08/10/2015 02:30"]; 


    if([startDate compare:EndDate] == NSOrderedAscending) 

     NSLog(@"Ascending"); 

    else 

     NSLog(@"Descending"); 

http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

檢查此鏈接瞭解更多日期格式

+0

謝謝@Gobi M,工作正常。 –

0

根據的NSDate的比較Apple Documentation

返回一個NSComparisonResult值,指示接收器和其他特定日期的時間排序。

- (NSComparisonResult)compare:(NSDate *)anotherDate 

參數anotherDate

的日期要與之比較的接收器。該值不能爲零。如果該值是零,則行爲是不確定的,並在Mac OS X的未來版本

返回值可以改變

如果:

接收器和anotherDate是完全相等,NSOrderedSame

接收機以後是在時間上比anotherDate,NSOrderedDescending

接收機較早在時間上比anotherDate,NSOrderedAscending 換句話說:

if ([date1 compare:date2] == NSOrderedSame) ... 

注意,這可能是你的具體情況更容易閱讀和寫:

if ([date2 isEqualToDate:date2]) ... 

Apple Documentation about this one