ios NSTimeInterval获取时间间隔

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

-(NSString *)getCurrentTime

{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

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

    NSString *dateTime = [formatter stringFromDate:[NSDate date]];

    self.startTime = dateTime;

    return startTime;

}

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

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

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

NSDate *date1 = [formatter dateFromString:startTime];

NSDate *date2 = [NSDate date];

NSTimeInterval aTimer = [date2 timeIntervalSinceDate:date1];


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

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

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

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






你可能感兴趣的:(iphone)