I've got several NSTimeInterval
s derived from previous calculations on various NSDate
s. Now I want to display these intervals to the user in days:hours:minutes:seconds
format.
Earlier in my app, I use this code to display the information in a slightly different context:
-(void)updateDurationLabel
{
//Which calendar
NSCalendar *calendar = [NSCalendar currentCalendar];
//Gets the componentized interval from the most recent time an activity was tapped until now
NSDateComponents *components= [calendar components:NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:self.startTime toDate:[NSDate date] options:0];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger minutes = [components minute];
NSInteger seconds =[components second];
// Converts the components to a string and displays it in the duration label, updated via the timer
cellLabelTempText = [NSString stringWithFormat:@"%02i:%02i:%02i:%02i",days,hours,minutes,seconds];
self.durationOrSleepLabel.text = cellLabelTempText;
}
However, in the current case, I would like for the desired NSString
to be produced using various already-obtained NSTimeInterval
s for use in several different labels, which are created on the fly.
Question:
Is there some way to get directly to an NSString
from an existing NSTimeInterval
, i.e., without going through the fromDate/toDate
rigamarole?
Thanks!
Update:
Pursuant to @Rich's answer below, I added this method, which skirted the math:
-(void) focusItemDurationCalculator
{
NSInteger days = ((NSInteger) focusItemDuration) / (60 * 60 * 24);
NSInteger hours = (((NSInteger) focusItemDuration) / (60 * 60)) - (days * 24);
NSInteger minutes = (((NSInteger) focusItemDuration) / 60) - (days * 24 * 60) - (hours * 60);
NSInteger seconds = ((NSInteger) round(focusItemDuration)) % 60;
actualDurationFocusItem = [NSString stringWithFormat:@"%02i:%02i:%02i:%02i",days,hours,minutes,seconds];
}
Works great!