-->

NSDateComponentFormatter Print 1 for NSTimeInverva

2019-09-06 20:45发布

问题:

I'm trying to have create a timer application and utilize iOS8's NSDateComponentsFormatter.

How can I output a properly-formatted string for NSTimeInterval values between 0 and 60?

As seen in the Swift playground, it seems to be returning a value of 1. I'd like to return a string with a format seen on NSTimeIntervals > 60, "0:12".

Note: I know that a I can manually take the time in seconds and calculate hour, minutes, etc. but that would not be using the NSDateComponentsFormatter.

// Playground - noun: a place where people can play

import UIKit

let dateComponentFormatter: NSDateComponentsFormatter = NSDateComponentsFormatter()
dateComponentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Positional

for (var timeInterval: NSTimeInterval = -1; timeInterval < 100; timeInterval++) {
    println("Time: \(dateComponentFormatter.stringFromTimeInterval(timeInterval))")
}

回答1:

I'm not entirely sure what format you need, but you can and should experiment with allowedUnits and zeroFormattingBehavior

For example this formatter configuration

let dateComponentFormatter: NSDateComponentsFormatter = NSDateComponentsFormatter()
dateComponentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Positional
dateComponentFormatter.allowedUnits = .CalendarUnitSecond | .CalendarUnitMinute
dateComponentFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehavior.allZeros

will create these string:

Time: 0:00
Time: 0:01
Time: 0:02
Time: 0:03
Time: 0:04
Time: 0:05
Time: 0:06
Time: 0:07
Time: 0:08
Time: 0:09
Time: 0:10