3

I'm using iOS charts to chart some data in my Swift iOS app including some times. The times are stored in Int variables as seconds but obviously people don't want to see 1 hour and 45 minutes on the Y axis as 6300 so I need to format it.

iOS charts lets you set use an NSNumberFormatter to do this like so

var formatter: NSNumberFormatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle
chartHolder.leftAxis.valueFormatter = formatter

But none of the styles available are suitable for what I need. I need it take a number of seconds and turn into, for example, 1h 45m. So I want to make a custom NSNumberFormatterStyle... But how do I do this?

Any help would be much appreciated.

365SplendidSuns
  • 3,175
  • 1
  • 21
  • 28

3 Answers3

3

A nice way to do that would be for you to create a subclass of NSNumberFormatter and use an NSDateFormatter inside of it to produce a time-like string output from your number. Here is an example:

class ElapsedTimeFormatter: NSNumberFormatter {

    lazy var dateFormatter: NSDateFormatter = {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        return dateFormatter
    }()

    override func stringFromNumber(number: NSNumber) -> String? {
        let timeInterval = NSTimeInterval(number)
        return dateFormatter.stringFromDate(NSDate(timeIntervalSinceReferenceDate: timeInterval))
    }
}

Test:

let formatter = ElapsedTimeFormatter()
let s = formatter.stringFromNumber(6300)
// Output: s = "01:45"
Clafou
  • 15,250
  • 7
  • 58
  • 89
2

This won't work with an NSNumberFormatterStyle - its options are too limited for you. What you should do, is subclass NSNumberFormatter, and override the stringFromNumber: function. There you can do all the string manipulation you want.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • Sure, this will work quick n dirty, but what about localization? If you are targeting iOS8.0 and higher, the recommended way to achieve what you want is by using [NSDateComponentsFormatter](https://developer.apple.com/library/prerelease/ios/documentation/Foundation/Reference/NSDateComponentsFormatter_class/index.html). – Coxy1989 Jul 21 '15 at 22:19
0
let formatter = NSDateComponentsFormatter()
formatter.zeroFormattingBehavior = .Pad
formatter.allowedUnits = [.Hour, .Minute, .Second]
formatter.unitsStyle = .Positional
let timeString = formatter.stringFromTimeInterval(Double(secondsElapsed))!
Asif
  • 681
  • 9
  • 17
Coxy1989
  • 160
  • 1
  • 6
  • How does this answer the OP's question? Can you provide some context? – brandonscript Jul 21 '15 at 20:17
  • The OP: "The times are stored in Int variables as seconds" " I need it take a number of seconds and turn into, for example, 1h 45m". This code does exactly that – Coxy1989 Jul 21 '15 at 22:00