Question

In my project, I have used NSDateFormatter to properly format the dates displayed in my application. To be more specific, here is an example:

English: 12:34 am
Arabic: ١٢:٣٤ ص

Looks great, shows the numerals that I need. However, I have a time counter/timer that is counting up/down in the app:

01:31:22 // HH:mm:ss

How would I properly localize this counter to be displayed as:

٠١:٣١:٢٢

I checked NSDateFormatter, but it doesn't really represent this particular use case, as far as I can see. NSNumberFormatter seems to work for currencies and percentages.


Why NSDateFormatter Doesn't Make Sense:

Because it has NSTimeZone property, and has am/pm suffix which are both useless when we want to use counters.

Was it helpful?

Solution

Right then, I think I have something for you. I've created a basic NSFormatter subclass, which will do the trick for you. All you need to do, it provide it with an NSNumber, that contains an NSTimeInterval.

The .h and .m are available here: https://github.com/WDUK/WDCountdownFormatter

And here is some example code using it, and yes, it should respect locales.

WDCountdownFormatter* format = [[WDCountdownFormatter alloc] init];
NSLog(@"70 - %@",[format stringForObjectValue:@(70)]);
NSLog(@"179 - %@",[format stringForObjectValue:@(179)]);
NSLog(@"-10 - %@",[format stringForObjectValue:@(-10)]); // Invalid, will return nil
NSLog(@"0 - %@",[format stringForObjectValue:@(0)]);
NSLog(@"9827193 - %@",[format stringForObjectValue:@(9827193)]);
NSLog(@"1 - %@",[format stringForObjectValue:@(1)]);

Produces

// UK English
2012-11-28 23:11:11.453 StackOverflow[28687:c07] 70 - 00:01:10
2012-11-28 23:11:11.456 StackOverflow[28687:c07] 179 - 00:02:59
2012-11-28 23:11:11.457 StackOverflow[28687:c07] -10 - (null)
2012-11-28 23:11:11.458 StackOverflow[28687:c07] 0 - 00:00:00
2012-11-28 23:11:11.458 StackOverflow[28687:c07] 9827193 - 2729:46:33
2012-11-28 23:11:11.459 StackOverflow[28687:c07] 1 - 00:00:01

// Egyptian Arabic
2012-11-28 22:59:54.057 StackOverflow[28400:c07] 70 - ٠٠:٠١:١٠
2012-11-28 22:59:54.659 StackOverflow[28400:c07] 179 - ٠٠:٠٢:٥٩
2012-11-28 22:59:55.473 StackOverflow[28400:c07] -10 - (null)
2012-11-28 22:59:56.464 StackOverflow[28400:c07] 0 - ٠٠:٠٠:٠٠
2012-11-28 22:59:57.311 StackOverflow[28400:c07] 9827193 - ٢٧٢٩:٤٦:٣٣
2012-11-28 23:10:36.657 StackOverflow[28400:c07] 1 - ٠٠:٠٠:٠١
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top