获取时间差转换成时、分、秒

  //获取当前时间

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

    //设定时间格式,这里可以设置成自己需要的格式

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

    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];

    

    NSString *yearStr = [currentDateStr substringWithRange:NSMakeRange(0, 4)];

    NSString *monthStr = [currentDateStr substringWithRange:NSMakeRange(5, 2)];

    NSString *dayStr = [currentDateStr substringWithRange:NSMakeRange(8, 2)];

    NSString *hourStr = [currentDateStr substringWithRange:NSMakeRange(11, 2)];

    NSString *minuteStr = [currentDateStr substringWithRange:NSMakeRange(14, 2)];

    NSString *ssStr = [currentDateStr substringWithRange:NSMakeRange(17, 2)];


    NSString *birStr = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@%@%@%@%@",yearStr,@"年",monthStr,@"月",dayStr,@"日",hourStr,@"时",minuteStr,@"分",ssStr,@"秒"];


//计算时间差

-(NSString *)dateTimeDifferenceWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{

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

//设置不同类型

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

    [date setDateFormat:@"HH:mm:ss"];

    

    NSDate *startD =[date dateFromString:startTime];

    NSDate *endD = [date dateFromString:endTime];

    NSTimeInterval start = [startD timeIntervalSince1970]*1;

    NSTimeInterval end = [endD timeIntervalSince1970]*1;

    NSTimeInterval value = end - start;

    

    //总共转成秒

    int miao = (int)value;


    int second = (int)value %60;//秒

    int minute = (int)value /60%60;

    int house = (int)value / (24 *3600)%3600;

    int day = (int)value / (24 *3600);

    NSString *str;


    if (day != 0) {

        str = [NSString stringWithFormat:@"耗时%d天%d小时%d分%d秒",day,house,minute,second];

   }else if (day==0 && house !=0) {

        str = [NSString stringWithFormat:@"耗时%d小时%d分%d秒",house,minute,second];

    }else if (day==0 && house==0 && minute!=0) {

        str = [NSString stringWithFormat:@"耗时%d分%d秒",minute,second];

    }else{

       str = [NSString stringWithFormat:@"耗时%d秒",second];

   }

    

    str = [NSString stringWithFormat:@"%d",second];


    return str;

}


你可能感兴趣的:(IOS)