【发布时间】:2014-06-13 04:46:05
【问题描述】:
我有几个NSTimeIntervals 来自之前对各种NSDates 的计算。现在我想以days:hours:minutes:seconds 格式向用户显示这些间隔。
在我的应用程序的早期,我使用此代码在稍微不同的上下文中显示信息:
-(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;
}
但是,在当前情况下,我希望使用各种已获得的NSTimeIntervals 生成所需的NSString,以便在动态创建的多个不同标签中使用。
问题:
有没有办法从现有的NSTimeInterval 直接访问NSString,即不通过fromDate/toDate rigamarole?
谢谢!
更新:
根据@Rich 在下面的回答,我添加了这种方法,它绕过了数学:
-(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];
}
效果很好!
【问题讨论】:
标签: ios nsstring nsdatecomponents nstimeinterval