NSDateComponentFormatter Print 1 for NSTimeInvervals <= 60

别等时光非礼了梦想. 提交于 2019-12-12 01:54:48

问题


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


来源:https://stackoverflow.com/questions/27870946/nsdatecomponentformatter-print-1-for-nstimeinvervals-60

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!