我希望你能帮助我:
我正在编写一个应该显示商店是否实际开放的应用程序。 为此我宣布每天和每个开放时间不同的变量/ NSDate-Objects喜欢(设置我之前完成的dateformatter):
NSDate *mondayMorningOpening = [dateFormatter dateFromString:@"08:00"];
NSDate *montagMorningClosing = [dateFormatter dateFromString:@"12:30"];
NSDate *mondayNoonOpening = [dateFormatter dateFromString:@"15:00"];
NSDate *montagNoonClosing = [dateFormatter dateFromString:@"21:30"];
我也为实际时间设置了一个NSDate:
NSString *tempDate1 = [dateFormatter stringFromDate:date];
NSDate *actualTime = [dateFormatter dateFromString:tempDate1];
现在我想计算实际时间是否在商店营业时间的时间范围之前或之后。我这样做了:
if ([actualTime earlierDate: mondayMorningClosing && [aktuelleZeit laterDate: mondayMorningOpening])
{
NSLog (@"The shop is open!");
}
else if ([actualTime earlierDate: mondayNoonClosing]&& [actualTime laterDate: mondayNoonOpening])
{
NSLog (@"The shop is open!");
}
else
{
NSLog (@"The shop is closed!");
}
但无论什么时候,它总是显示“商店是开放的!”。
也许你知道该怎么做才能正确显示开场状态......
答案 0 :(得分:1)
你误解了earlyDate和laterDate的含义。方法不是“isEarlierDate”和“isLaterDate”,它们不返回BOOL。这些方法返回一个NSDate对象,两个日期的早期(或后期)。 '不是零对象,所以它们总是被评估为真。
比较两个日期的时间间隔:
if ([actualTime timeIntervalSinceDate: mondayMorningClosing]<0 && [aktuelleZeit timeIntervalSinceDate: mondayMorningOpening]>0)
{
NSLog (@"The shop is open!");
}
答案 1 :(得分:1)
您可以比较两个日期,但结果您将拥有一个NSDate:
if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(@"date1 is earlier than date2");
}
答案 2 :(得分:1)
如果你有2个日期,你可以确定这两个日期之间是否有NSDate
:
- (BOOL)isDate:(NSDate *)date betweenFirstDate:(NSDate *)firstDate andSecondDate:(NSDate *)secondDate
{
BOOL isEqualToFirstOrSecond = [date compare:firstDate] == NSOrderedSame || [date compare:secondDate] == NSOrderedSame;
BOOL isBetweenFirstAndSecond = [date compare:firstDate] == NSOrderedDescending && [date compare:secondDate] == NSOrderedAscending;
return isEqualToFirstOrSecond || isBetweenFirstAndSecond;
}