1

我希望你能帮我解决这个问题:

我正在编写一个应用程序,该应用程序应显示商店是否实际营业。为此,我为每一天和每个开放时间声明了不同的变量/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!");
        }

但无论是什么时候,它总是显示“商店开门了!”。

也许您知道该怎么做,我可以正确显示开放状态...

4

3 回答 3

1

If you have 2 dates you can determine if an NSDate is between those two like this:

- (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;
}
于 2012-11-05T21:27:13.523 回答
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");
}
于 2012-11-05T21:16:28.627 回答
1

您误解了 earlyDate 和 laterDate 的含义。这些方法不是“isEarlierDate”和“isLaterDate”,它们不返回 BOOL。这些方法返回一个 NSDate 对象,即两个日期中较早(或较晚)的日期。它们不是nil 对象,所以它们总是被评估为真。

比较两个日期的时间间隔:

if ([actualTime timeIntervalSinceDate: mondayMorningClosing]<0 && [aktuelleZeit timeIntervalSinceDate: mondayMorningOpening]>0)
{
    NSLog (@"The shop is open!");
}
于 2012-11-05T21:10:48.883 回答