获取时间间隔 iphon

- (NSString *)intervalSinceNow_YY_MM : (NSDate *) theDate {
    
    NSDate *eDate, *lDate;
    
    eDate = [theDate earlierDate: [NSDate date]];
    lDate = [theDate laterDate: [NSDate date]];
    
    NSDateFormatter *yyDateformater=[[NSDateFormatter alloc]init];
    [yyDateformater setDateFormat:@"YYYY"];
    NSDateFormatter *mmDateformater=[[NSDateFormatter alloc]init];
    [mmDateformater setDateFormat:@"MM"];
    
    NSInteger eYear, eMonth, lYear, lMonth, intervalYear, intervalMonth;
    
    eYear = [[yyDateformater stringFromDate:eDate] intValue];
    lYear = [[yyDateformater stringFromDate:lDate] intValue];
    eMonth = [[mmDateformater stringFromDate:eDate] intValue];
    lMonth = [[mmDateformater stringFromDate:lDate] intValue];
    
    if (lMonth > eMonth) {
        intervalMonth = lMonth - eMonth;
        intervalYear = lYear - eYear;
    }
    else if(lMonth < eMonth) {
        intervalMonth = 12 - eMonth + lMonth;
        intervalYear = lYear - eYear - 1;
    }
    else {
        intervalYear = lYear - eYear;
        return [NSString stringWithFormat:@"%d年",intervalYear];
    }
    
    return  [NSString stringWithFormat:@"%d年%d月",intervalYear,intervalMonth];
    
}

 

 

官方的这个 API 可能会省事一些

NSDate *begin = [NSDate date];
    
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *d = [cal components:unitFlags fromDate:begin toDate:[NSDate date] options:0];
        int i = 0;    
        i = [d second];
    

你可能感兴趣的:(Date,api,Components)