2010-03-30 20 views
22

cómo puedo comparar dos fechas devolver el número de días. Ej .: Faltan X días de la Copa. mira mi código.¿Cómo puedo comparar dos fechas, devolver un número de días

NSDateFormatter *df = [[NSDateFormatter alloc]init]; 
    [df setDateFormat:@"d MMMM,yyyy"]; 
    NSDate *date1 = [df dateFromString:@"11-05-2010"]; 
    NSDate *date2 = [df dateFromString:@"11-06-2010"]; 
    NSTimeInterval interval = [date2 timeIntervalSinceDate:date1]; 
    //int days = (int)interval/30; 
    //int months = (interval - (months/30))/30; 
    NSString *timeDiff = [NSString stringWithFormat:@"%dMissing%d days of the Cup",date1,date2, fabs(interval)]; 

    label.text = timeDiff; // output (Missing X days of the Cup) 
+0

Puede mira esta respuesta http://stackoverflow.com/questions/13236719/number-of-days-between-two-nsdate-objects ayudó a resolver mi problema –

Respuesta

35

De Apple's example, básicamente utilizar un NSCalendar:

NSDate * date1 = <however you initialize this>; 
NSDate * date2 = <...>; 

NSCalendar *gregorian = [[NSCalendar alloc] 
       initWithCalendarIdentifier:NSGregorianCalendar]; 

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; 

NSDateComponents *components = [gregorian components:unitFlags 
              fromDate:date1 
              toDate:date2 options:0]; 

NSInteger months = [components month]; 
NSInteger days = [components day]; 
+0

OP también tendrá que cambiar el formato de fecha a @ "MM-dd-aaaa" . – DyingCactus

+0

Me lo perdí la primera vez. Esa es probablemente la razón por la que no estaba obteniendo lo que quería. – darelf

3

Puede utilizar siguiente categoría:

@interface NSDate (Additions) 

-(NSInteger)numberOfDaysUntilDay:(NSDate *)aDate; 
-(NSInteger)numberOfHoursUntilDay:(NSDate *)aDate; 

@end 

@implementation NSDate (Additions) 
const NSInteger secondPerMunite = 60;  
const NSInteger munitePerHour = 60; 
const NSInteger hourPerDay = 24; 

-(NSInteger)numberOfDaysUntilDay:(NSDate *)aDate 
{ 
    NSInteger selfTimeInterval = [aDate timeIntervalSinceDate:self]; 
    return abs(selfTimeInterval/(secondPerMunite * munitePerHour * hourPerDay));  
} 

-(NSInteger)numberOfHoursUntilDay:(NSDate *)aDate 
{ 
    NSInteger selfTimeInterval = [aDate timeIntervalSinceDate:self]; 
    return abs(selfTimeInterval/(secondPerMunite * munitePerHour)); 
} 
@end 
+4

Este es un enfoque realmente incorrecto. Use los métodos NSCalendar en su lugar. – Andrew

0

necesidad de llamar a este método y el grupo 2 fechas única que desea calcular diferentemente.

-(void) calculateSleepHours:(NSDate *)sleepDate :(NSDate *)wakeStr 
{ 

    if (sleepDate !=nil && wakeStr!=nil) {`enter code here` 

    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; 
    [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ssZ"]; 
    NSDate *date1 = [ApplicationManager getInstance].sleepTime;; 

    NSDate *date2 = [ApplicationManager getInstance].wakeupTime; 

    NSCalendar *gregorian = [[NSCalendar alloc] 
          initWithCalendarIdentifier:NSGregorianCalendar]; 

    NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit; 

    NSDateComponents *components = [gregorian components:unitFlags 
               fromDate:date1 
                toDate:date2 options:0]; 

    NSInteger months = [components month]; 
    NSInteger days = [components day]; 
    NSInteger hours = [components hour]; 
    NSInteger minute=[components minute]; 
    NSInteger second=[components second]; 
    DLog(@"Month %ld day %ld hour is %ld min %ld sec %ld ",(long)months,(long)days,(long)hours,(long)minute,(long)second); 

    sleepHours.text=[NSString stringWithFormat:@"Hour %ld Min %ld Sec %ld",(long)hours,(long)minute,(long)second]; 
    } 
} 
0

Prueba esta categoría:

@interface NSDate (DateUtils) 

-(NSInteger)numberOfDaysUntilDay:(NSDate *)aDate; 

@end 

@implementation NSDate (DateUtils) 

-(NSInteger)numberOfDaysUntilDay:(NSDate *)aDate 
{ 

    NSCalendar *calendar = [[NSCalendar alloc] 
          initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 

    NSDateComponents *components = [calendar components:NSCalendarUnitDay 
               fromDate:self 
                toDate:aDate options:kNilOptions]; 

    return [components day]; 

} 

@end 

Puede utilizar esta categoría mediante la adición de una importación:

#import "NSDate+DateUtils.h" 

Y llamaremos a partir de su código:

NSInteger days = [myDate numberOfDaysUntilDay:someOtherDate]; 
Cuestiones relacionadas