2013-05-16 211 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 
} 
相關問題