2013-12-16 2 views
6

В моем приложении я хочу проверить, находится ли текущее время до или после времени, сохраненного в переменной.Сравните два значения времени в ios?

как мой time1 является [email protected]"08:15:12"; и мой time2 является [email protected]"18:12:8";

так я хочу сравнить между time1 и time2.Currently эти переменные находятся в NSString формате.

Ниже приведен код, используемый для получения времени, и я не знаю, как их сравнить.

КОД:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
     dateFormatter.dateFormat = @"HH:MM:SS"; 
     [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 
     NSLog(@"ewetwet%@",[dateFormatter stringFromDate:now]); 

Пожалуйста, помогите мне

+0

Посмотрите на эту ссылку http://stackoverflow.com/questions/13748007/nsstring-to-timeinterval –

+0

вы экономите время как строки, есть вы считаете, сэкономить время как TimeInterval, используйте 'dateWithTimeIntervalSince1970' ?? – johnMa

ответ

36

Используйте следующий код, чтобы сделать обращенного из NSString в NSDate и сравнить их.

NSString *time1 = @"08:15:12"; 
NSString *time2 = @"18:12:08"; 

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"HH:mm:ss"]; 

NSDate *date1= [formatter dateFromString:time1]; 
NSDate *date2 = [formatter dateFromString:time2]; 

NSComparisonResult result = [date1 compare:date2]; 
if(result == NSOrderedDescending) 
{ 
    NSLog(@"date1 is later than date2"); 
} 
else if(result == NSOrderedAscending) 
{ 
    NSLog(@"date2 is later than date1"); 
} 
else 
{ 
    NSLog(@"date1 is equal to date2"); 
} 
+0

, сравнивая этот способ, дает мне значения мусора в date1 и date2. Проверьте мой вопрос здесь. Http://stackoverflow.com/questions/25571399/nsdate-are-coming-as-garbage-values-with-the-time-comparision?noredirect1_comment39936953_25571399 –

1

Вы можете использовать этот link

Согласно Apple, документации NSDate сравнения:

Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date. 

- (NSComparisonResult)compare:(NSDate *)anotherDate 

Parameters anotherDate 

The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X. 

Return Value 

If: 

The receiver and anotherDate are exactly equal to each other, NSOrderedSame 

The receiver is later in time than anotherDate, NSOrderedDescending 

The receiver is earlier in time than anotherDate, NSOrderedAscending 

Другими словами:

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

Обратите внимание, что может быть проще читать и писать так:

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

См Apple Documentation об этом. Если вы чувствуете какую-либо проблему, вы также можете использовать эту ссылку here. Здесь вы можете найти ответ Нельсона Брайана.

Я сделал это в моем конце следующим образом-

NSDate * [email protected]"firstDate"; 
NSDate * [email protected]"SecondDate"; 


NSTimeInterval timeDifferenceBetweenDates = [shiftDateFieldObj timeIntervalSinceDate:currentDateObj]; 

Вы также можете получить интервал времени в зависимости от разницы во времени между датами. Надеюсь, это поможет.

+0

но как я могу преобразовать значение времени в NSdate? – Bangalore

+1

Простой, используя NSDate Formattor Yiou может изменить вашу дату в соответствии с вами – iEinstein

+0

У меня нет даты только времени, возможно ли это? – Bangalore

1

Прежде всего, необходимо преобразовать времени строку NSDate =>Converting time string to Date format iOS.

Затем используйте следующий код

NSDate *timer1 =... 
NSDate *timer2 =... 

     NSComparisonResult result = [timer1 compare:timer2]; 
     if(result == NSOrderedDescending) 
     { 
      // time 1 is greater then time 2 
     } 
     else if(result == NSOrderedAscending) 
     { 
      // time 2 is greater then time 1 
     } 
     else 
     { 
      //time 1 is equal to time 2 
     } 
5
// Use compare method. 

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

    NSDate *startDate = [formatter dateFromString:@"2012-12-07 7:17:58"]; 
    NSDate *endDate = [formatter dateFromString:@"2012-12-07 7:17:59"]; 


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

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

    } else { 
     NSLog(@"dates are the same"); 

    } 

    // Way 2 
    NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:startDate]; 

    double minutes = timeDifference/60; 
    double hours = minutes/60; 
    double seconds = timeDifference; 
    double days = minutes/1440; 

    NSLog(@" days = %.0f,hours = %.2f, minutes = %.0f,seconds = %.0f", days, hours, minutes, seconds); 

    if (seconds >= 1) 
     NSLog(@"End Date is grater"); 
    else 
     NSLog(@"Start Date is grater"); 
Смежные вопросы