[IOS]ios NSTimeInterval获取时间间隔

//转载:http://blog.163.com/shj_0920@126/blog/static/164415423201211143736501/

想在程序开始或者进入某个界面 ,到结束程序或退出某个界面,获取到这个持续时间. 获取到这个时间还需要转化一个取得时分秒.

-(NSString *)getCurrentTime

{

    NSDateFormatter *formatter = [[NSDateFormatteralloc]init];

    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

   NSString *dateTime = [formatterstringFromDate:[NSDatedate]];

   self.startTime = dateTime;

   return startTime;

}

date1代表开始时间,在开始计时的地方调用 [self getCurrentTime]; 在结束时的方法里写如下代码:

NSDateFormatter *formatter = [[NSDateFormatteralloc]init];

[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *date1 = [formatter dateFromString:startTime];

NSDate *date2 = [NSDatedate];

NSTimeInterval aTimer = [date2timeIntervalSinceDate:date1];


int hour = (int)(aTimer/3600);

int minute = (int)(aTimer -hour*3600)/60;

int second =aTimer -hour*3600 -minute*60;

NSString *dural = [NSStringstringWithFormat:@"%d%d%d", hour, minute,second];

你可能感兴趣的:(ios)