我想在iOS中进行两次比较。我在我的数组中有时间列表我只想检查当前时间是否匹配任何一个数组值。可以任何帮助如何做到这一点。我搜索整个互联网我不知道。
我看到了this question answer,但我无法得到确切的结果。
答案 0 :(得分:1)
根据NSDate比较的Apple文档:
Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.
- (NSComparisonResult)compare:(NSDate *)anotherDate
参数anotherDate
比较接收器的日期。该值不得为零。
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]) ...
答案 1 :(得分: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(long long values)。如果相同则时间,日期和年份相同,否则不同。
我希望这个答案是您的问题的权利.......
答案 2 :(得分:0)
为什么不检查自1970年以来的间隔并比较整数值..
long long int i = [[NSDate date] timeIntervalSince1970];
我希望这会有所帮助。如果您有 NSString 形式的值,那么您首先需要将它们转换为 NSDate
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ssSSSSSS";
NSDate *d = [dateFormatter dateFromString:@"your date string"];