如何计算NSDateFormatter的时差

时间:2012-03-01 15:21:26

标签: objective-c xcode

我使用以下代码将2个标签设置为当前时间:

NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"hh:mma"];
        time2.text = [dateformatter stringFromDate:[NSDate date]];
        [dateformatter release];
        labelCount++;

单击按钮时,标签1将更改为当前时间,再次单击按钮时,标签2将更改为当前时间,但我希望能够更改第三个标签以显示这些时间之间的差异。任何帮助/指导将不胜感激。

2 个答案:

答案 0 :(得分:2)

[date2 timeIntervalSinceDate:date1]将为您提供以秒为单位的时间间隔,但如果您希望差异显示为小时:分钟,那么这也会起作用。

- (IBAction)updateTime:(id)sender {
static NSUInteger labelCount = 0;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mma"];
NSDate *date1 = nil;
NSDate *date2 = nil;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents;

switch (labelCount) {
    case 0:
        self.time1.text = [dateFormatter stringFromDate:[NSDate date]];
        labelCount++;
        break;
    case 1:
        self.time2.text = [dateFormatter stringFromDate:[NSDate date]];
        labelCount++;
        break;
    case 2:
        date1 = [dateFormatter dateFromString:self.time1.text];
        date2 = [dateFormatter dateFromString:self.time2.text];
        NSUInteger calendarUnits = NSHourCalendarUnit | NSMinuteCalendarUnit;
        dateComponents = [calendar components:calendarUnits fromDate:date1 toDate:date2 options:0];
        self.time3.text = [NSString stringWithFormat:@"%i:%i", [dateComponents hour], [dateComponents minute]];
        labelCount = 0;
        break;
    default:
        break;
}

}

注意:如果您不使用arc,则需要在此代码中添加适当的版本。

答案 1 :(得分:0)

NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];