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.
Share
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.
With the
fabs()wrapping thetimeIntervalSinceDate:there, you won’t get a negative time based on the ordering of the receiver and argument fortimeIntervalSinceDate:. 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.