ios 两个时间相差多少天多少小时多少分多少秒

今天用到一个时间类,之前写过但是一时找不到了在此记录一下方便以后查看。

- (NSString *)dateTimeDifferenceWithStartTime:(NSString *)startTime endTime:(NSString *)endTime
{
    NSDateFormatter *date = [[NSDateFormatter alloc]init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *startDate =[date dateFromString:startTime];
    NSDate *endDdate = [date dateFromString:endTime];
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponents = [cal components:unitFlags fromDate:startDate toDate:endDdate options:0];
    
    // 天
    NSInteger day = [dateComponents day];
    // 小时
    NSInteger house = [dateComponents hour];
    // 分
    NSInteger minute = [dateComponents minute];
    // 秒
    NSInteger second = [dateComponents second];
    
    NSString *timeStr;
    
    if (day != 0) {
        timeStr = [NSString stringWithFormat:@"%zd天%zd小时%zd分%zd秒",day,house,minute,second];
    }
    else if (day==0 && house !=0) {
        timeStr = [NSString stringWithFormat:@"%zd小时%zd分%zd秒",house,minute,second];
    }
    else if (day==0 && house==0 && minute!=0) {
        timeStr = [NSString stringWithFormat:@"%zd分%zd秒",minute,second];
    }
    else{
        timeStr = [NSString stringWithFormat:@"%zd秒",second];
    }
    
    return timeStr;
}

+ (NSString *)dateAppendSeconds:(NSInteger)seconds
{
    
    
    NSTimeInterval value =  diffTime;
    
    // 天
    int day = (int)value / (24 *3600);
    // 小时
    int house = (int)value / 3600%3600;
    // 分
    int minute = (int)value /60%60;
    // 秒
    int second = (int)value %60;
    
    NSString *timeStr;
    
    if (day != 0) {
        timeStr = [NSString stringWithFormat:@"%d天%d小时%d分%d秒",day,house,minute,second];
    }
    else if (day==0 && house !=0) {
        timeStr = [NSString stringWithFormat:@"%d小时%d分%d秒",house,minute,second];
    }
    else if (day==0 && house==0 && minute!=0) {
        timeStr = [NSString stringWithFormat:@"%d分%d秒",minute,second];
    }
    else{
        timeStr = [NSString stringWithFormat:@"%d秒",second];
    }
    
    return timeStr;
}

你可能感兴趣的:(ios 两个时间相差多少天多少小时多少分多少秒)