2013-05-21 3 views
0

Я пытаюсь сравнить два раза в iOS. У меня есть список раз в моем массиве, я просто хочу проверить текущее время, соответствующее любому значению массива. может помочь, как это сделать. я искал весь интернет, я не понял.Как сравнить два раза в iOS

Я видел this question answer, но я не могу получить точный результат.

+0

Текущее время с точностью до точки? Я сомневаюсь, что '[dateArray containsObject: [NSDate date]]' будет работать из коробки ... –

+0

проверить это может быть, это дает вам некоторую идею. http://stackoverflow.com/questions/13229142/how-to-compare-current-date-to-previous-date-in-iphone/13229194#13229194 –

+0

Вы пробовали метод сравнения NSDate? если он возвращает NSOrderedSame, даты совпадают. – Vertig0

ответ

1

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

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

- (NSComparisonResult)compare:(NSDate *)anotherDate 

параметров anotherDate

Дата, с которой для сравнения приемник. Это значение не должно быть nil.

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 

In other words: 

if ([date1 compare:date2]==NSOrderedSame) ... 
Note that it might be easier to read and write this : 

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

Почему бы вам не проверить интервал с 1970 года и сравните целое значение ..

long long int i = [[NSDate date] timeIntervalSince1970]; 

Я надеюсь, что это будет help.Also, если у вас есть значения в виде NSString то вам сначала нужно преобразовать их в NSDate

 NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; 
     dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ssSSSSSS"; 
     NSDate *d = [dateFormatter dateFromString:@"your date string"]; 
+1

Вместо этого проверьте временной интервал между двумя датами непосредственно с 'timeIntervalSinceDate:'. Кроме того, 'NSTimeInterval' является' double', а не целым числом. –

+0

Да, точно, это тоже сработает .. –

1
-(NSString *)determineDateFromstring:(long long)date 
{ 
    NSTimeInterval interval=date; 
    NSDate *currentTime=[NSDate dateWithTimeIntervalSince1970:interval/1000]; 

    NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]; 

    NSNumber *myDateInString=[NSNumber numberWithLongLong:[[NSDate date] timeIntervalSince1970]*1000]; 
    NSTimeInterval inte=[myDateInString longLongValue]; 
    NSDate *todayTime=[NSDate dateWithTimeIntervalSince1970:inte/1000]; 



    NSCalendar *currentcalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDateComponents *components = [currentcalendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:todayTime]; 

    int currentday=[components day]; 
    int currentyear=[components year]; 

    NSCalendar *paramtercalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDateComponents *parametercomponents = [paramtercalendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:currentTime]; 

    int currentday1=[parametercomponents day]; 
    int currentyear1=[parametercomponents year]; 


    if (currentday==currentday1) { 
    Nslog(date are same); 

    }else if(currentyear==currentyear1) { 
    Nslog(year are same); 

    }else{ 

    } 

} 

, если вы хотите проверить две даты, равны или нет, тогда вы можете сравнить NStimeIntervals (длинные длинные значения). если они совпадают, то время, дата и год одинаковы в других отношениях.

Надеюсь, этот ответ будет правильным на ваш вопрос .......

Смежные вопросы