When I try to calculate the time elapsed using Date Components the date is one second off. Why is this?
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:timeStarted toDate:[[NSDate date]addTimeInterval:+1.0] options:0];
timeElapsed = [sysCalendar dateFromComponents:conversionInfo];
My temporary fix is to add one second, but I want to understand why it is happening or if there is a better fix.
EDIT: It is not one second off, but it is rounding down. When I get the time interval in seconds (which brings it down to decimal places) it comes out to be 1.9, 2.9, 3.9 and is showing 00:00:01, 00:00:02, 00:00:03 respectively. How can I get it to round up?
You can round a double (NSTimeInterval) to an integer with:
The long integer ’rounded’ will now contain 8. You can now cast this back to a time interval.
and use that with the NSDate functions.
So to create an NSDate with only full seconds you can use:
or to round off an existing NSDate’s subseconds: