2010-06-20 21 views
7

Come è possibile confrontare due NSDate e restituire il tempo tra di essi.Confronto di due NSDate

Ad esempio:

2010-06-20 14:29:41 -0400 
2010-06-20 14:53:29 -0400 

dovrebbe restituire qualcosa come: 23 o 24 (minuti), arrotondando i secondi perché non ho davvero bisogno dei secondi.

risposta

11

provare qualcosa di simile:

int intervall = (int) [date1 timeIntervalSinceDate: date2]/60; 
+0

funziona alla grande. Grazie mille. –

+1

Si noti che questo può valutare un numero negativo di minuti, a seconda di quale data è precedente. O nega il numero se è negativo, o usa la funzione 'abs' o' fabs'. –

+0

grazie come sempre per quel suggerimento @ Peter –

2

Qui il frammento di codice completo per confrontare due NSDate che si possono trovare più utile in base alla query.

NSCalendar *myCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSString *str [email protected]"12:15, 01 15 2012 AM"; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"hh:mm, dd MM yy a"]; 

NSDate *refDate = [formatter dateFromString:str]; 
NSDate *today = [NSDate date]; 



NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit; 
NSDateComponents *difference = [myCal components:unitFlags fromDate:refDate  toDate:today options:0]; 
NSLog(@"%@",difference); 

------------------------------ quello che otterrete è -------- ---------------------------------

Anno civile: 0 Mese: 0 Giorno: 0 Ora: 1 Minuto: 19