First we establish the format of the date like so. I am using HH:MM:SS format. Format yours to suit your saved string.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"HH:mm:ss"];
The second part is referencing your strings. I create a new reference just to keep it tidy when converting String Date to NSDate. In my example I have declared a reference to Core Data in my .h file so I reference as follows.
NSString * StringTime1 = self.coreDataReference.time1;
NSString * StringTime2 = self.coreDataReference.time2;
Convert the strings to date:
NSDate *time1 = [dateFormat dateFromString:StringTime1];
NSDate *time2 = [dateFormat dateFromString:StringTime2];
I next get the difference by getting the time interval between the times. I am comparing the latest saved time (time2) against the first save time (time1). This method essentially subtracts whatever time is allocated second from the first, which in this case tim2 subtracts time1. You will see why in a moment.
NSTimeInterval distanceBetweenDates = [time2 timeIntervalSinceDate:time1];
For displaying purposes, I convert the time which is now a double (NSTimeInterval is a double, check https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html for more information) and then convert them into hours, minutes and second values.
int timeInt = (int) distanceBetweenDates;
//I convert the values into the time value
int hours = timeInt / 3600;
int minutes = (timeInt / 60) % 60;
int seconds = timeInt % 60;
FInally we display the results in log and if you have a label display there as well.
NSLog(@"The total time is: %02u:%02u:%02u", hours, minutes, seconds);
NSString * time = [NSString stringWithFormat:@"%02u:%02u:%02u", hours, minutes, seconds];
self.totalLoginTimeLabel.text = time;
I hope this helps anyone investigating.
The whole code here:
-(void) calculateTimeIntervalFromStrings{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"HH:mm:ss"];
NSString * StringTime1 = self.coreDataReference.time1;
NSString * StringTime2 = self.coreDataReference.time2;
NSDate *time1 = [dateFormat dateFromString:StringTime1];
NSDate *time2 = [dateFormat dateFromString:StringTime2];
NSTimeInterval distanceBetweenDates = [time2 timeIntervalSinceDate:time1];
int timeInt = (int) distanceBetweenDates;
//I convert the values into the time value
int hours = timeInt / 3600;
int minutes = (timeInt / 60) % 60;
int seconds = timeInt % 60;
NSLog(@"The total time is: %02u:%02u:%02u", hours, minutes, seconds);
NSString * time = [NSString stringWithFormat:@"%02u:%02u:%02u", hours, minutes, seconds];
self.timeDifferenceLabel.text = time;
}
To call this method, place in your viewDidLoad method like so:
[self calculateTimeIntervalFromStrings];