从按下按钮获取时间(按住)

时间:2013-07-30 18:17:54

标签: ios nsdate nstimeinterval

当试图获得时间时,我没有达到预期值。

当我跑步时,时间是19:59。在timeDifferenceString中,Value为71976.894206。 我认为这是现在的时间 我算出了71976/3600 = 19,99 h
0,99 * 60 = 59.4 m
0,4 * 60 = 24 s

所以我得到的时间是19:59:24。但我希望得到第一次和第二次之间的差异,而不是以秒为单位的当前时间。

我只想得到按住按钮的时间 以及没有按下按钮的时间
(如果我按下按钮则第一次启动,如果我按下另一个按钮则停止)。

- (IBAction)pressTheButton:(id)sender {
NSDate * now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm:ss:SSS"];
NSString *currentTime = [formatter stringFromDate:now];    

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components; //= [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:10];

NSDate* firstDate = [NSDate date];
NSString *getTime = [formatter stringFromDate:now];

getTime = [formatter stringFromDate:firstDate];

if (iX==0)
{
    components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
    firstDate = [calendar dateFromComponents:components];
    getTime = [formatter stringFromDate:firstDate];
    //firstDate = [NSDate date];//[dateFormatter dateFromString:@"00:01:00:090"];
}

components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
//NSDate* secondDate = [dateFormatter dateFromString:@"10:01:02:007"];
NSDate * secondDate = [calendar dateFromComponents:components];
getTime = [formatter stringFromDate:firstDate];

NSTimeInterval timeDifference = [firstDate timeIntervalSinceDate:secondDate];
NSString *timeDifferenceString = [NSString stringWithFormat:@"%f", timeDifference];

timeDiff[iX] = [timeDifferenceString intValue];
[timeLabel setText:timeDifferenceString];
iX++;
}

如果你对我的问题有更好的解决方案,请帮助我。

1 个答案:

答案 0 :(得分:2)

在这里查看UIControlEventTouchDown,UIControlEventTouchUpInside:http://developer.apple.com/library/ios/#documentation/uikit/reference/UIControl_Class/Reference/Reference.html

然后我想你想要在某种ivar或属性(UIControlEventTouchDown)中按下时存储NSDate,当你释放按钮(UIControlEventTouchUpInside或UIControlEventTouchUpOutside)然后在该日期调用-timeIntervalSinceDate:时存储另一个NSDate。所以它看起来大致如下:

- (IBAction)pressedDown:(id)sender {
    self.pressedDownDate = [NSDate date];
}

- (IBAction)touchedUp:(id)sender {
    NSDate *now = [NSDate date];
    NSLog(@"Time passed: %d", [now timeIntervalSinceDate:self.pressedDownDate]);
}