检查今天的日期是否在开始日期和结束日期之间

时间:2013-05-16 07:08:51

标签: ios objective-c

当前日期不应该在开始日期之前和结束日期之后,但它可以等于开始日期结束日期

我该如何修改代码?

for(AllBookings *book in bookarray)
{

    NSString *startdte = book.StartDate; //taking start date from array
    NSString *enddte = book.EndDate;
    NSDate *start = [self getDateFromJSON:startdte];
    NSDate *end = [self getDateFromJSON:enddte];
    NSDate *now = [NSDate date];

    NSTimeInterval fromTime = [start timeIntervalSinceReferenceDate];
    NSTimeInterval toTime = [end timeIntervalSinceReferenceDate];
    NSTimeInterval currTime = [[NSDate date] timeIntervalSinceReferenceDate];

    if((fromTime<currTime) && (toTime>=currTime))//checking if currnt is in btw strt n end
    {
        success = TRUE;
        break;

    }
    else {
        success = FALSE;
    }

}

3 个答案:

答案 0 :(得分:1)

以下是我在我的应用程序中使用的工作代码,我已根据您的要求进行了更改:

 -(void)isSuitableTime{
  NSDateFormatter *df = [[NSDateFormatter alloc] init];
  [df setDateFormat:@"HH:mm"];

   NSDate *currentTime = [NSDate date];
   NSString *currentTimeString = [df stringFromDate: currentTime];

   NSDate *gpsTimeCurrent= [df dateFromString:currentTimeString];
   NSDate *gpsTimeFrom = [df dateFromString:@"09:00" ];
   NSDate *gpsTimeTo = [df dateFromString:@"17:00"];

   NSTimeInterval intervalFromTimeToCurrent = 
             [gpsTimeCurrent timeIntervalSinceDate:gpsTimeFrom];

   NSTimeInterval intervalCurrentToTimeTo = 
                 [gpsTimeTo timeIntervalSinceDate:gpsTimeCurrent];

   NSLog(@"intervalToTimeToCurrent is %f",intervalCurrentToTimeTo);

   if ((intervalFromTimeToCurrent>0) && (intervalCurrentToTimeTo >0)) {
                NSLog(@"In my time range");
    } 
    else {
    NSLog(@"Out of my time range");
    }

 }

答案 1 :(得分:0)

使用此方法配合

- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
       return [date compare:firstDate] == NSOrderedDescending && [date compare:lastDate]  == NSOrderedAscending;
}

答案 2 :(得分:0)

使用NSDate的compare:方法代替if (current > fromTime)

From the class reference:

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.


you can use

if([current compare: From] == NSOrderedDescending||NSOrderedSame
   && [current compare: Totime]== NSOrderedAescending||NSOrderedSame)
{
  // Current is between to and From 
}