更新:請注意,此解決方案特定於您的情況,並假定商店開放時間不會跨越兩天。例如,如果開放時間從星期一晚上9點到星期二上午10點,它將不起作用。自晚上10點晚上9點以後,但不是上午10點以前(一天內)。所以記住這一點。
我製作了一個函數,它會告訴你一個日期的時間是否在兩個其他日期之間(忽略年,月和日)。還有第二個輔助函數,它爲您提供了一個新的NSDate,其年,月和日組件被「中和」(例如設置爲某個靜態值)。
這個想法是將年份,月份和日期組件設置爲在所有日期之間相同,以便比較僅依賴於時間。
我不確定它是否是最有效的方法,但它的工作原理。
- (NSDate *)dateByNeutralizingDateComponentsOfDate:(NSDate *)originalDate {
NSCalendar *gregorian = [[[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
// Get the components for this date
NSDateComponents *components = [gregorian components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: originalDate];
// Set the year, month and day to some values (the values are arbitrary)
[components setYear:2000];
[components setMonth:1];
[components setDay:1];
return [gregorian dateFromComponents:components];
}
- (BOOL)isTimeOfDate:(NSDate *)targetDate betweenStartDate:(NSDate *)startDate andEndDate:(NSDate *)endDate {
if (!targetDate || !startDate || !endDate) {
return NO;
}
// Make sure all the dates have the same date component.
NSDate *newStartDate = [self dateByNeutralizingDateComponentsOfDate:startDate];
NSDate *newEndDate = [self dateByNeutralizingDateComponentsOfDate:endDate];
NSDate *newTargetDate = [self dateByNeutralizingDateComponentsOfDate:targetDate];
// Compare the target with the start and end dates
NSComparisonResult compareTargetToStart = [newTargetDate compare:newStartDate];
NSComparisonResult compareTargetToEnd = [newTargetDate compare:newEndDate];
return (compareTargetToStart == NSOrderedDescending && compareTargetToEnd == NSOrderedAscending);
}
我用這段代碼來測試它。您可以看到年,月和日被設置爲一些隨機值,並且不會影響時間檢查。
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];
NSDate *openingDate = [dateFormatter dateFromString:@"2012:03:12 12:30:12"];
NSDate *closingDate = [dateFormatter dateFromString:@"1983:11:01 17:12:00"];
NSDate *targetDate = [dateFormatter dateFromString:@"2034:09:24 14:15:54"];
if ([self isTimeOfDate:targetDate betweenStartDate:openingDate andEndDate:closingDate]) {
NSLog(@"TARGET IS INSIDE!");
}else {
NSLog(@"TARGET IS NOT INSIDE!");
}
我錯過了什麼,或者你真的只是在尋找' - [NSDate比較:]'? – 2012-10-27 16:48:56
問題是,首先不會比較日期和時間,而不僅僅是時間?如上所述,這些打開和關閉時間對象的時間字段只是初始化的。日,月,年字段不是。 – Nosrettap
在這種情況下,您可以使用[NSDateComponents類。](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateComponents_Class/Reference/Reference.html) – 2012-10-27 16:56:12