Reputation: 17160
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?
Upvotes: 2
Views: 1734
Reputation: 2124
DateComponentsFormatter
, available from iOS 8, works nicely, especially if you want easy localization. Here are some examples.
let duration : TimeInterval = 11735 // seconds
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .abbreviated
let text1 = formatter.string(from: duration) // "3h 15m 35s"
// choose a longer unit style:
formatter.unitsStyle = .short
let text2 = formatter.string(from: duration) // "3 hr, 15 min, 35 sec"
// easy localization:
formatter.calendar?.locale = Locale(identifier: "da_DK")
let text3 = formatter.string(from: duration) // "3 t., 15 min. og 35 sek."
// approximate to whole minutes:
formatter.calendar?.locale = Locale(identifier: "en_US")
formatter.includesApproximationPhrase = true
formatter.allowedUnits = [.hour, .minute]
let text4 = formatter.string(from: duration) // "About 3 hr, 15 min" - (not rounding up)
// approximation AND localization (Apple has a bug to fix):
formatter.calendar?.locale = Locale(identifier: "da_DK")
formatter.includesApproximationPhrase = true
formatter.allowedUnits = [.hour, .minute]
let text5 = formatter.string(from: duration) // "About 3 t. og 15 min." - Ugh!
Upvotes: 6
Reputation: 9754
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.
Upvotes: 4
Reputation: 131398
NSNumberFormatter
isn't really a fit for this. You could shoehorn an NSDateFormatter
into doing what you want, but those are designed for displaying dates and times of day, not elapsed times like you want.
Take a look at this thread on SO on the subject:
Formatting seconds into hh:ii:ss
In particular @dreamlax answer.
If you don't need to support automatic localization that's the simplest way to do it.
Upvotes: 1