Nếu bạn đang nhắm mục tiêu ở iOS 8 hoặc OS X 10.10 trở lên, điều này sẽ dễ dàng hơn rất nhiều. Lớp mới NSDateComponentsFormattercho phép bạn chuyển đổi một NSTimeIntervalgiá trị đã cho từ giá trị của nó trong vài giây thành một chuỗi được bản địa hóa để hiển thị cho người dùng. Ví dụ:
Objective-C
NSTimeInterval interval = 326.4;
NSDateComponentsFormatter *componentFormatter = [[NSDateComponentsFormatter alloc] init];
componentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
componentFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;
NSString *formattedString = [componentFormatter stringFromTimeInterval:interval];
NSLog(@"%@",formattedString); // 5:26
Nhanh
let interval = 326.4
let componentFormatter = NSDateComponentsFormatter()
componentFormatter.unitsStyle = .Positional
componentFormatter.zeroFormattingBehavior = .DropAll
if let formattedString = componentFormatter.stringFromTimeInterval(interval) {
print(formattedString) // 5:26
}
NSDateCompnentsFormattercũng cho phép đầu ra này ở dạng dài hơn. Có thể tìm thấy thêm thông tin trong bài báo NSFormatter của NSHipster . Và tùy thuộc vào những lớp nào bạn đang làm việc (nếu không NSTimeInterval), có thể thuận tiện hơn để chuyển cho trình định dạng một thể hiện của NSDateComponentshoặc hai NSDateđối tượng, điều này cũng có thể được thực hiện thông qua các phương thức sau.
Objective-C
NSString *formattedString = [componentFormatter stringFromDate:<#(NSDate *)#> toDate:<#(NSDate *)#>];
NSString *formattedString = [componentFormatter stringFromDateComponents:<#(NSDateComponents *)#>];
Nhanh
if let formattedString = componentFormatter.stringFromDate(<#T##startDate: NSDate##NSDate#>, toDate: <#T##NSDate#>) {
// ...
}
if let formattedString = componentFormatter.stringFromDateComponents(<#T##components: NSDateComponents##NSDateComponents#>) {
// ...
}