2012-05-20 11 views
5

Ho 3 variabili;Controllare se l'ora e la data sono tra una data e un'ora particolari

startDate - Wed Apr 12 endDate - Wed Jun 11 timeDuration - 11.00 am from 11.00 pm. (questa è una stringa, 11AM è l'ora di inizio e 12PM è l'ora di fine)

1.) Ora, ho bisogno di ottenere la data e l'ora corrente ([NSDate date]) e controllare se la data corrente è tra il startDate e endDate e quindi controllare se l'ora corrente è tra il timeDuration (come tra 11.00am from 11.00pm)

2.) Se l'ora corrente è tra la durata di tempo (come tra 11.00 am from 11.00 pm) ho bisogno di calcolare il tempo rimanente al seguente scenari;

a.) Se il tempo è 10am, ho bisogno di calcolare il tempo per l'ora di inizio che è 11.00am. (la risposta è 1 hour).

b.) Se il tempo è 11.45AM, dal momento che il tempo è maggiore del tempo di avvio (che era 11.00am) ho bisogno di calcolare il tempo rimanente per l'ora di fine (che è 11.00pm).

c.) Se l'ora è 11.45pm, poiché l'ora è maggiore dell'ora di fine (ovvero 11.00pm), è necessario stampare un NSLog che dice "Ora superata".

+0

possibile duplicato di [Come verificare se un NSDate si verifica tra due altre NSDates] (http://stackoverflow.com/questions/1072848/how-to-check-if-an-nsdate-occurs-between-two-other-nsdates), http://stackoverflow.com/questions/1987506, http: // stackoverflow. it/questions/9807370 /, http://stackoverflow.com/questions/8295008/ –

+0

Cosa succede se l'ora corrente è alle 12:15? È troppo tardi da ieri, o troppo presto oggi ?? – lnafziger

+0

Che tipo di variabile è startDate? Un NSDate o NSString? – lnafziger

risposta

1

L'idea di base è quella di convertire il numero startDate e il in effettivo NSDate e confrontarli con la data corrente. Quindi se la data corrente è nell'intervallo corretto, aggiungi le ore di inizio e di fine alla data corrente per ottenere un punto specifico in tempo per l'ora di inizio e di fine. Una volta che hai queste date, è possibile utilizzare i compare e timeIntervalSinceDate metodi di NSDate per ottenere i valori di cui avete bisogno:

// NOTE: NO error checking is being done in this code. 

// Starting variables 
NSString *startDateString  = @"Wed Apr 12"; 
NSString *endDateString  = @"Wed Jun 11"; 
NSString *timeDurationString = @"11.00 am from 11.00 pm"; 

// Get the current date 
NSDate *currentTime  = [NSDate date]; 
NSCalendar *cal   = [NSCalendar currentCalendar]; 
NSDateComponents 
     *currentDateComps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit 
            fromDate:currentTime]; 

// Add the current year onto our date string 
NSString *startDateStringWithYear = [NSString stringWithFormat:@"%@ %d", startDateString, currentDateComps.year]; 
NSString *endDateStringWithYear = [NSString stringWithFormat:@"%@ %d", endDateString, currentDateComps.year]; 

// Calculate NSDate's for start/endDate 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"EEE MM dd yyyy"]; 
NSDate *startDate = [formatter dateFromString:startDateStringWithYear]; 
NSDate *endDate = [formatter dateFromString:endDateStringWithYear]; 

// Return if today's date is not between the start and end dates 
if ([startDate compare:currentTime] == NSOrderedDescending || 
    [endDate compare:currentTime] == NSOrderedAscending) 
{ 
    return; 
} 

// Break the timeDurationString into separate words 
NSArray *timeDurationStringWords = [timeDurationString componentsSeparatedByString:@" "]; 

// Calculate NSDate's for the start time for today: 
NSString *startTimeString = [timeDurationStringWords objectAtIndex:0]; 
currentDateComps.hour  = [[startTimeString substringToIndex:2] intValue]; 
currentDateComps.minute = [[startTimeString substringFromIndex:3] intValue]; 
if ([[timeDurationStringWords objectAtIndex:1] isEqualToString:@"pm"]) 
{ 
    currentDateComps.hour += 12; 
} 
NSDate *startTime   = [cal dateFromComponents:currentDateComps]; 

// And now the end time for today 
NSString *endTimeString = [timeDurationStringWords objectAtIndex:3]; 
currentDateComps.hour  = [[endTimeString substringToIndex:2] intValue]; 
currentDateComps.minute = [[endTimeString substringFromIndex:3] intValue]; 
if ([[timeDurationStringWords objectAtIndex:4] isEqualToString:@"pm"]) 
{ 
    currentDateComps.hour += 12; 
} 
NSDate *endTime   = [cal dateFromComponents:currentDateComps]; 

// Now we have what we really want: A specific start time, current time, and end time. 

// Check to see if we are waiting to start: 
if ([startTime compare:currentTime] == NSOrderedDescending) { 
    NSTimeInterval minutesToStartTime = [startTime timeIntervalSinceDate:currentTime]/60; 
    NSLog(@"Start time is in %02d+%02d", (int)(minutesToStartTime/60), (int)minutesToStartTime % 60); 
    return; 
} 

// Check to see if we are late: 
if ([endTime compare:currentTime] == NSOrderedAscending) { 
    NSLog(@"Time Exceeded"); 
    return; 
} 

// We are between the two times: 
NSTimeInterval minutesToEndTime = [endTime timeIntervalSinceDate:currentTime]/60; 
NSLog(@"End time is in %02d+%02d", (int)(minutesToEndTime/60), (int)minutesToEndTime % 60); 
+0

Tuttavia, se 'currentTime' è uguale a' startDateString' o 'endDateString' eseguirà il blocco' if ([startDate compare: currentTime] == NSOrderedDescending .... 'e non calcola il tempo rimanente Come posso risolvere questo problema? – Illep

+0

Cambia '== NSOrderedDescending' a'! = NSOrderedAscending' (che in pratica significa '<=' invece di solo '<. ' – lnafziger

+0

Ti è stato d'aiuto? – lnafziger

1

È possibile utilizzare - (NSComparisonResult)compare:(NSDate *)anotherDate
confrontare la data corrente con startDate e endDate.

NSComparisonResult 

enum { 
    NSOrderedAscending = -1, 
    NSOrderedSame, 
    NSOrderedDescending 
};  

Esempio:

NSDate *currentDate = [NSDate date]; 
if (([currentDate compare:startDate ] == NSOrderedDescending) && 
    ([currentDate compare:endDate ] == NSOrderedAscending)) { 

    //currentDate is between startDate and endDate. 
} 

o dare un'occhiata a this soluzione bbum.

+0

Puoi mostrarmi un esempio? – Illep

+0

Ma come posso mostrare il tempo (domanda 2)? – Illep

Problemi correlati