时间戳。两次之间的差异
问题描述:
我试图做一个时间戳应用程序,您可以通过一个按钮捕捉时间。时间戳。两次之间的差异
当按钮被按下时,它打印出当前时间00:00:00
。 当第二次按下按钮时,它再次打印当前时间(即00:00:15
)。
然后我希望它计算两个时间戳(10秒)之间的时间差。
我是新来的Objective-C,我一直在坐着这个小小的问题几个小时。在正确的方向上有一个指针会很好。
我遇到了问题timeIntervalSinceDate
。这里是代码:
- (IBAction)checkButton:(id)sender {
if (buttonPress) {
self.checkInStamp = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];
checkInTime.text = [timeFormatter stringFromDate:checkInStamp];
buttonPress = false;
}
else {
self.checkOutStamp = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];
checkOutTime.text = [timeFormatter stringFromDate:checkOutStamp];
NSTimeInterval timeDifference = [checkOutStamp timeIntervalSinceDate:checkInStamp];
totalDuration.text = @"%d", timeDifference; //<-This gives "Expression result unused on build"
}
}
谢谢任何帮助!
答
2个NSDate
对象使用[NSDate timeIntervalSinceDate:]
方法(reference)获得并作为NSTimeInterval
(一个typedef
倒是double
)表示之间的差异:
NSTimeInterval difference = [self.checkOutStamp timeIntervalSinceDate:self.checkInStamp];
NSLog(@"Difference is %f seconds", difference);