Calculate time difference in Cocoa

北城余情 提交于 2019-12-02 23:21:31
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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!