好吧,我是这样整理的:
- (void)fijaTiempoInicio
{
//getting current day
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:~ NSTimeZoneCalendarUnit fromDate:[NSDate date]];
[dateComponents setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Spain"]];
NSDate *currentDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
//extracting year, month and day from current date
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"dd"];
NSString *currentDayString = [NSString stringWithFormat:@"%@",[df stringFromDate:currentDate]];
[df setDateFormat:@"MM"];
NSString *currentMonthString = [NSString stringWithFormat:@"%@",[df stringFromDate:currentDate]];
[df setDateFormat:@"yyyy"];
NSString *currentYearString = [NSString stringWithFormat:@"%@", [df stringFromDate:currentDate]];
NSDateFormatter *ft = [[NSDateFormatter alloc]init];
[ft setTimeZone:[NSTimeZone localTimeZone]];
[ft setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *tempDate = [NSString stringWithFormat:@"%@-%@-%@ %@",currentYearString,currentMonthString,currentDayString,txtTiempoInicioTramo.text];
NSLog(@"tempDate= %@",tempDate);
startTime = [ft dateFromString:tempDate];
NSLog(@"startTime= %@",startTime);
然后,另一种方法计算两个 NSDate 之间的差异,这是一个以毫秒为单位的数字 - 一个浮点数
- (IBAction)btnCapturarTiempo:(id)sender
{
NSDateFormatter *formatCarTime = [[NSDateFormatter alloc]init];
[formatCarTime setDateFormat:@"HH:mm:ss"];
[formatCarTime setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Madrid"]];
carTime = [NSDate date];
difference = [carTime timeIntervalSinceDate:startTime];
labelTiempoCoche.text = [NSString stringWithFormat:@"%f",difference];