I have got two timevalues in the format: %H%M%S (E.G.161500)
These values are text-based integers.
Is there a simple function in Cocoa that calculates the difference between these two integers using a 60 seconds and minutes scale?
So if
time 1 = 161500
time 2 = 171500
timedifference = 003000
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"HHmmss"];
NSDate *date1 = [dateFormatter dateFromString:@"161500"];
NSDate *date2 = [dateFormatter dateFromString:@"171500"];
NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; // diff = 3600.0
The class for manipulating dates is NSDate
. The method for getting time intervals is -timeIntervalSinceDate:
. The result is a NSTimeInterval
value, which is a double
representing the interval in seconds.
You can create a NSDate
object from a NSString
with +dateWithString:
, provided that your date is formatted as 2001-03-24 10:45:32 +0600.
try this code.
- (NSTimeInterval)intervalBetweenDate:(NSDate *)dt1 andDate:(NSDate *)dt2 {
NSTimeInterval interval = [dt2 timeIntervalSinceDate:dt1];
NSLog(@"%f",interval);
return interval;
}
I would create an NSFormatter subclass to parse time values in that format from input data (you can put one on a text field to automatically convert user input, or use it to parse from a data source in code). Have it return the combined number of seconds as an NSTimeInterval (double representing seconds) wrapped in an NSNumber. From there it's easy to subtract the difference, and display it using the same NSFormatter class you created. In both parsing and displaying values, you're the one responsible to write code converting from seconds to hours:minutes:seconds or whatever format you like. You could also convert these values to an NSDate like mouviciel mentioned, if it makes sense for your application. Just keep in mind you're always going to be storing the time difference from a reference date, usually Jan 1st 1970 (NSDate has methods to do this for you).