Якщо ви орієнтуєтесь на iOS 8 або OS X 10.10, це просто стало набагато простіше. Новий NSDateComponentsFormatterклас дозволяє перетворити задане NSTimeIntervalз його значення за секунди в локалізований рядок, щоб показати користувача. Наприклад:
Ціль-С
NSTimeInterval interval = 326.4;
NSDateComponentsFormatter *componentFormatter = [[NSDateComponentsFormatter alloc] init];
componentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
componentFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;
NSString *formattedString = [componentFormatter stringFromTimeInterval:interval];
NSLog(@"%@",formattedString); // 5:26
Швидкий
let interval = 326.4
let componentFormatter = NSDateComponentsFormatter()
componentFormatter.unitsStyle = .Positional
componentFormatter.zeroFormattingBehavior = .DropAll
if let formattedString = componentFormatter.stringFromTimeInterval(interval) {
print(formattedString) // 5:26
}
NSDateCompnentsFormatterтакож дозволяє, щоб цей результат був у більш тривалих формах. Більш детальну інформацію можна знайти в статті NSHipster NSFormatter . І залежно від того, з якими класами ви вже працюєте (якщо ні NSTimeInterval), може бути зручніше передати форматiру екземпляр NSDateComponentsабо два NSDateоб’єкти, що можна зробити так само за допомогою наступних методів.
Ціль-С
NSString *formattedString = [componentFormatter stringFromDate:<#(NSDate *)#> toDate:<#(NSDate *)#>];
NSString *formattedString = [componentFormatter stringFromDateComponents:<#(NSDateComponents *)#>];
Швидкий
if let formattedString = componentFormatter.stringFromDate(<#T##startDate: NSDate##NSDate#>, toDate: <#T##NSDate#>) {
// ...
}
if let formattedString = componentFormatter.stringFromDateComponents(<#T##components: NSDateComponents##NSDateComponents#>) {
// ...
}