swift - What am I doing wrong with NSDateComponentsFormatter? -
i found out new-to-ios8 class nsdatecomponentsformatter, lets format time intervals rather dates. cool. i've written code more times care think about. decided try , use in playground, can't work. here's (swift) code:
var componentsformatter = nsdatecomponentsformatter() componentsformatter.allowedunits = .calendarunithour | .calendarunitminute | .calendarunitsecond componentsformatter.unitsstyle = .positional let interval: nstimeinterval = 345.7 let intervalstring = componentsformatter.stringfromtimeinterval(interval) println("interval string = \(intervalstring)")
this displays
interval string = nil
i've tried various things, no joy. have working example using new class, or can spot i'm missing?
(i speak objective-c too, if have sample code in objective-c works well.)
swift 3.1 • xcode 8.3.2
extension formatter { static let datecomponents: datecomponentsformatter = { let formatter = datecomponentsformatter() formatter.calendar = calendar(identifier: .iso8601) formatter.unitsstyle = .full formatter.includesapproximationphrase = true formatter.includestimeremainingphrase = true formatter.maximumunitcount = 2 formatter.zeroformattingbehavior = .default formatter.allowsfractionalunits = false formatter.allowedunits = [.year, .month, .weekofmonth, .day, .hour, .minute, .second] return formatter }() } extension timeinterval { var remainingtime: string { return formatter.datecomponents.string(from: self) ?? "" } }
let interval = 60.0 * 60 * 24 * 7 let intervalstring = interval.remainingtime // "about 1 week remaining"
positional time
extension formatter { static let positional: datecomponentsformatter = { let formatter = datecomponentsformatter() formatter.unitsstyle = .positional formatter.zeroformattingbehavior = .default formatter.allowedunits = [.hour, .minute, .second] return formatter }() } extension timeinterval { var hourminutesecond: string { return formatter.positional.string(from: self) ?? "" } } let time = 345.7 let positional = time.hourminutesecond // "5:45"
Comments
Post a Comment