2013-05-16 210 views
-1

当前日期不应该在开始日期结束日期后,但它可以等于开始日期结束日期检查今天的日期开始日期和结束日期之间落在

我该如何修改代码?

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; 
    } 

} 
+1

在这里检查你发现许多完全相同的问题。 –

+0

检查此链接http://stackoverflow.com/questions/6112075/ios-compare-two-dates – Durgaprasad

回答

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"); 
    } 

} 
0

使用此方法队友

- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate { 
     return [date compare:firstDate] == NSOrderedDescending && [date compare:lastDate] == NSOrderedAscending; 
} 
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 
} 
相关问题