计算时差

//传入的开始时间和结束时间是下面的格式。这里只给了小时和分钟。你可以通过修改时间格式传入自己的时间字符串格式来计算时间差

starTime  @"11:00"
endTime   @"13:25"

- (NSString *)returnDurationTime:(NSString *)starTime endTime:(NSString *)endTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"HH:mm"];
    NSDate* stardate = [formatter dateFromString:starTime];
    NSDate* enddate = [formatter dateFromString:endTime];
    
    //把时间转化成时间戳
    int starTimeSp =  [stardate timeIntervalSince1970];
    int endTimeSp =  [enddate timeIntervalSince1970];
    //通过时间戳差值计算相差时间
    int sp = endTimeSp - starTimeSp;

    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:sp];
    NSString *labStr = [NSString stringWithFormat:@"%@",confromTimesp];
    NSString *labstr1 = [labStr substringFromIndex:11];
    NSString *labstr2 = [labstr1 substringToIndex:5];
  
    return labstr2;
}

你可能感兴趣的:(计算时差)