rat*_*p99 2 nsstring nsdatecomponents nstimeinterval ios
我NSTimeInterval从以前的各种计算中得到了几个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;
}
Run Code Online (Sandbox Code Playgroud)
然而,在当前情况下,我希望NSString使用各种已经获得的NSTimeIntervals 来生产所需的s,以用于在运行中创建的若干不同标签.
题:
有没有办法直接NSString从现有的NSTimeInterval,即没有通过fromDate/toDaterigamarole?
谢谢!
更新:
根据@ 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];
}
Run Code Online (Sandbox Code Playgroud)
效果很好!
为什么不NSTimeInterval自己使用并计算每个组件.您也可以取消使用[NSDate date]和使用timeIntervalSinceNow.
您可以使用整数除法来丢弃每个组件的小数部分.
// Use abs if you don't care about direction
NSTimeInterval duration = abs([self.startTime timeIntervalSinceNow]);
NSInteger days = ((NSInteger) duration) / (60 * 60 * 24);
NSInteger hours = (((NSInteger) duration) / (60 * 60)) - (days * 24);
NSInteger minutes = (((NSInteger) duration) / 60) - (days * 24 * 60) - (hours * 60);
NSInteger seconds = ((NSInteger) round(duration)) % 60;
Run Code Online (Sandbox Code Playgroud)
这应该比处理更快NSDateComponents.这不是你想要的,但确实涵盖了这个:D
没有经过fromDate/toDate rigamarole
| 归档时间: |
|
| 查看次数: |
4191 次 |
| 最近记录: |