Search code examples
iosobjective-ctimensnumberformatterios-charts

Convert seconds to hours, minutes, seconds using NSNumberFormatter


I am using the Charts framework so I can display stats and it takes simple number values, e.g 1, 5, 17, 99, 1,574 etc and plots them on a graph.

It give the choice to set an NSNumberFormatter to display those value more elegantly.

The numbers I am using are total number of seconds. E.g. 660 seconds, 1080 seconds.

How can I use the NSNumberFormatter to make my number display as hours, minutes, seconds, instead of purely total seconds?


Solution

  • If you are talking about the xAxis labels, they are strings, not numbers, so you can directly pass date strings to xAxis values.

    If you are talking about yAxis labels, as you know the y axis represents number, that's why we can draw charts.

    If you really want to do so, you can write your own NSNumberFormatter subclass and override stringFromNumber, to manually translate number to the time you want. And use this formatter for yAxis.valueFormatter.

    It's simple math you just to have to divide 60/3600 to get minutes or hours.

    The point is, you have to know how you want to translate the number. e.g. if '60' on yAxis label is really meaning '60 sec', otherwise your chart is meaningless.