问题
I've tried all the time calculating examples I found on this site but somehow I'm getting 0 as value every time. I'm new to IOS and the NSDate is giving me a run for it's money :)
I want to record time A when I press button "startStop", and then record time B when I press it again. Pressing it a second time (deselecting) has to calculate the time elapsed between these 2 dates. So far I have this:
-(IBAction)buttonClick {
NSDate *startStopDate = [NSDate alloc];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm:ss"];
NSString *currentTime = [[NSString alloc] init];
NSString *currentTime2 = [[NSString alloc]init];
NSDate *start =[ [NSDate alloc]init];
NSDate *stop = [[NSDate alloc] init];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
if (startStop.selected==NO) {
NSLog(@"started");
[startStop setSelected:YES];
startStopDate = [NSDate date];
currentTime = [formatter stringFromDate:startStopDate];
NSLog(@"Current timestarted is %@",currentTime);
startTime.text = currentTime;
start = [formatter dateFromString:currentTime];
}
else {
NSLog(@"Selected");
[startStop setSelected:NO];
startStopDate = [NSDate date];
currentTime2 = [formatter stringFromDate:startStopDate];
NSLog(@"Current time is %@",currentTime2);
stopTime.text = currentTime2;
stop = [formatter dateFromString:currentTime2];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:start
toDate:stop
options:0];
NSInteger hours = [components hour];
NSInteger minutes = [components minute];
NSInteger seconds = [components second];
NSLog(@"hello %d, %d, %d", hours, minutes, seconds);
}
}
My labels give the correct hour:minute output when pressed, but I can't seem to get them to transfer to the date calculation. I've been trying numerous variations with dateFromString and stringFromDate and multiple date/string objects as you can see, but so far I only get big negative numbers or just zero as result. Any help appreciated ;)
Greets, Nick
回答1:
That's because start is a local variable. When the button is clicked the second time, your code will skip the if block and go straight to the else block, leaving the start variable allocated but not initialized to anything useful. You need to store this start value outside of a local context if you want to use it to calculate the difference between the start and stop times.
来源:https://stackoverflow.com/questions/9882410/calculate-time-elapsed-between-pressing-the-same-button-twice