TJ15
TJ15

Reputation: 363

How to calculate Time difference from NSDateFormatter

I have 2 labels that I set to the current time using the following code:

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

When a button is clicked label one will change to the current time, when button is click again label 2 will change to the current time but I want to be able to change a third label to display the difference between these times. Any help/guidance would be greatly appreciated.

Upvotes: 1

Views: 970

Answers (2)

solydest
solydest

Reputation: 383

[date2 timeIntervalSinceDate:date1] will give you the time interval in seconds, but if you want the difference displayed as hours:minutes then this will work too.

- (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;
}

}

Note: if you aren't using arc then you'll need to add the appropriate releases to this code.

Upvotes: 2

Parag Bafna
Parag Bafna

Reputation: 22930

NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];

Upvotes: 0

Related Questions