-2

我有两个日期,比如 currentdate 和 getDate,我想比较 getdate 是旧的还是新的或相等的。

我试过这个供你参考:

    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    NSString *currentDate = [dateFormatter stringFromDate:today]; 
    // Current_date (7/26/2013)

    NSString *getdate=[outDateformatter1 stringFromDate:bDt1]; 
   // Get_date (7/26/2010)

    NSComparisonResult result;        
    result = [currentDate compare:getdate]; // comparing two dates
    if(result==NSOrderedAscending)
        NSLog(@"today is less");

  I need this, Original result getdate is old date.

但是它不能正常工作,请任何人为此建议我。

提前致谢

4

4 回答 4

0
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    NSDate *serDate;

    NSDate *endDate;

    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    serDate = [formatter dateFromString:@"2012-12-07 7:17:58"];

    endDate = [formatter dateFromString:@"2012-12-07 08:43:30"];
    NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:serDate];

    double minutes = timeDifference / 60;

    double hours = minutes / 60;

    double seconds = timeDifference;

    double days = minutes / 1440;
    NSLog(@" days = %.0f,hours = %.2f, minutes = %.0f,seconds = %.0f", days, hours, minutes, seconds);


    if (hours > 1.30)
        return 1;
    else
        return 0;
于 2013-07-26T05:09:33.463 回答
0

使用compare方法。

if ([currentdate compare: getDate] == NSOrderedDescending) {
    NSLog(@"currentdate is later than getDate");        

} else if ([currentdate compare:getDate] == NSOrderedAscending) {
    NSLog(@"currentdate is earlier than getDate");

} else {
    NSLog(@"dates are the same");

}
于 2013-07-26T05:11:00.413 回答
0
//Use this function to compare current date to another date  

 - (NSInteger)numberOfDaysUntil:(NSDate *)aDate {
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:aDate options:0];

    //NSLog(@"Number of days  >>>%d",[components day]);

    return [components day];

// then use this logic 

 if ([self numberOfDaysUntil:date]==0)
    {
        NSLog(@"Today");
    }
    else if ([self numberOfDaysUntil:date]== -1)
    {
        NSLog(@"Yesterday");
    }
    else{

        // if return is -2 then date is two date before current date .

// if return is 1 then date is one future date than current day

    }
于 2013-07-26T05:11:25.417 回答
0
for that you have to import NSDate-Utilities.h and .m file. 

NSDateFormatter *df=[[NSDateFormatter alloc] init]; [df setDateFormat:@"MM/dd/yyyy"];

float oldDate = [[df dateFromString:[dic valueForKey:@"end_date"]] timeIntervalSinceNow];

 if (oldDate < 0) {
     //past date
}
else if (oldDate > 0){
    //future date
}
else{
    //same date
}
于 2013-07-26T05:11:53.693 回答