I have two time values in HH:mm format that I need to compare, and return how many minutes they differ by. For example comparing 18:30 and 19:45 should return 1:15. I've read up on NSDate, NSCalendar, and so on, but I am confused as to how they all work together and how I would create an NSDate with only a time, not an entire date.
You could use NSDateFormatter to create NSDate objects given strings in "HH:mm" format, and then use -[NSDate timeIntervalSinceDate:] to find the number of seconds between the two times. NSDate encapsulates a full date - you can't have it represent only a time - so the NSDate objects created will be a time on a specific date (the reference date, Jan 1st 1970, from my testing) in the local time zone. You'll need to decide for yourself whether you need a more robust solution to fit your needs since your needs are unclear.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];
NSDate *time1 = [formatter dateFromString:@"18:30"];
NSDate *time2 = [formatter dateFromString:@"19:45"];
[formatter release];
NSTimeInterval deltaTime = fabs([time1 timeIntervalSinceDate:time2]);
NSString *result = [NSString stringWithFormat:@"%d:%d", (int)(deltaTime/3600), (int)(deltaTime/60)%60];
With the fabs()
wrapping the timeIntervalSinceDate:
there, you won't get a negative time based on the ordering of the receiver and argument for timeIntervalSinceDate:
. You can adjust that if needed.
Note: The above probably isn't the best or most efficient way ever to determine the result, but I was just aiming to illustrate the concept, not optimize unnecessarily.