计算两天之间的天数errror目标c

时间:2015-05-21 05:12:46

标签: objective-c date

你好我想在目标c中计算今天和过去日期10-05-2015之间的天数。但是当我把条件如下,如果条件的话,它总是进入。我的代码中应该出现什么问题?

     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    // this is imporant - we set our input date format to match our input string
    // if format doesn't match you'll get nil from your string, so be careful

    [dateFormatter setDateFormat:@"dd-MM-yy hh:mm a"];

    NSDate *Startdate = [[NSDate alloc] init];
    Startdate = [dateFormatter dateFromString:eventstartdate];

    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];

    // this is imporant - we set our input date format to match our input string
    // if format doesn't match you'll get nil from your string, so be careful

    [dateFormatter1 setDateFormat:@"MM-dd-yy hh:mm a"];
    NSDate *CurrentDate = [[NSDate alloc] init];

    CurrentDate = [dateFormatter1 dateFromString:Currentdate];

    NSDate *startDate= Startdate;
    NSDate *endDate = CurrentDate ;
    if ([CurrentDate earlierDate:Startdate])
    {
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *differenceComponents = [calendar components:NSCalendarUnitDay fromDate:startDate toDate:endDate options:0];
        NSInteger numDays = differenceComponents.day;
    }
    else
    {
        UIAlertView *AlertMsg =[[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"Event is scheduled at %@",eventstartdate] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [AlertMsg show];
    }

获取相同类型的日期格式,如2015-05-21 12:00为startdate和结束日期,除了我给出了不同的格式。

我的代码有问题吗?

1 个答案:

答案 0 :(得分:4)

来自Apple : NSDate compare:的文档

  

返回NSComparisonResult值,该值指示接收方的时间顺序和另一个给定日期。

     

- (NSComparisonResult)compare:(NSDate *)anotherDate

     

参数 anotherDate

     

比较日期   接收器。该值不得为零。   如果值为nil,则行为为   未定义,将来可能会改变   Mac OS X的版本。

     

返回值

     

如果:

     

接收者和另一个日子是   完全相同,   的 NSOrderedSame

     

接收器晚些时候进入   时间比另一个日期,   的 NSOrderedDescending

     

接收器是   比其他日期早,   的 NSOrderedAscending

换句话说:

如果您想查看相同的日期

if ([date1 compare:date2] == NSOrderedSame) 
{
    NSLog(@"dates are the same");
}

如果您想查看以后的日期

if ([date1 compare:date2] == NSOrderedDescending) 
{
     NSLog(@"date1 is later than date2");
}

如果您想查看更早的日期

if ([date1 compare:date2] == NSOrderedAscending) 
{
    NSLog(@"date1 is earlier than date2");
}