Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 2 dates in seconds ios

I have an app where content is displayed to the user. I now want to find out how many seconds a user actually views that content for. So in my header file, I've declared an

 NSDate *startTime;  NSDate *endTime; 

Then in my viewWillAppear

 startTime = [NSDate date]; 

Then in my viewWillDisappear

endTime = [NSDate date]; NSTimeInterval secs = [endTime timeIntervalSinceDate:startTime]; NSLog(@"Seconds --------> %f", secs); 

However, the app crashes, with different errors sometimes. Sometimes it's a memory leak, sometimes it's a problem with the NSTimeInterval, and sometimes it crashes after going back to the content for a second time.

Any ideas on to fix this?

like image 826
Adam Altinkaya Avatar asked Nov 01 '13 09:11

Adam Altinkaya


People also ask

How can I get the difference between two dates in IOS?

Getting difference between two dates is easy. You should know how to play between the dates. We will be using DateFormatter class for formatting the dates. Instances of DateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.

How do you find the difference between two dates and seconds?

We have the startDate and endDate which we can convert both to timestamps in milliseconds with getTime . Then we subtract the timestamp of endDate by the timestamp of startDate . This will return the timestamp difference in milliseconds. So we divide the difference by 1000 to get the difference in seconds.

How do I get seconds between two dates in Swift?

date(from: "2021/12/24 00:00") let newYear = formatter. date(from: "2022/01/01 00:00") print(newYear! - xmas!) This is the number of seconds between the two dates.

How do I get the difference between two dates in Objective C?

NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"]; NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"]; NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1]; int numberOfDays = secondsBetween / 86400; NSLog(@"There are %d days in between the two dates.", numberOfDays);


1 Answers

since you are not using ARC, when you write

startTime = [NSDate date];

you do not retain startTime, so it is deallocated before -viewWillDisappear is called. Try

startTime = [[NSDate date] retain];

Also, I recommend to use ARC. There should be much less errors with memory management with it, than without it

like image 143
medvedNick Avatar answered Sep 23 '22 14:09

medvedNick