问题描述
我需要在iPhone上以hh:mm:ss格式显示计时器,但希望它本地化。例如,芬兰在时间分量(hh.mm.ss)之间使用句号而不是冒号。如果我处理的是时间,那么Apple的NSDateFormatter可以解决这个问题,但我需要显示大于24的小时数。
I need to display a timer in "hh:mm:ss" format on the iPhone, but want it localized. Finland, for example uses a period instead of a colon between the time components (hh.mm.ss). Apple's NSDateFormatter would do the trick if I was dealing with a "time" but I need to display hours much greater than 24.
我无法制作NSDate / NSDateFormatter工作,因为当在一台与秒...
I have not been able to make an NSDate/NSDateFormatter work because when you make one with seconds...
NSDate *aDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTotalSeconds];
...每86,400秒(一天的价值)NSDate自动递增日,小时,分钟,并且秒数回到零。我需要让它在任何数秒内工作而不会翻滚。例如,我想要显示24:00:01秒(或芬兰的24.00.01)。
... every 86,400 seconds (one day's worth) NSDate automatically increments the day and hours, minutes, and seconds go back to zero. I need to make it work on an any number of seconds without rolling over. For example, with 86,401 seconds I want to display 24:00:01 (or 24.00.01 in Finland).
我的代码管理总秒数很好,所以唯一的问题我有显示器。一个简单的......
My code manages total seconds fine, so the only problem I have is the display. A simple...
[NSString stringWithFormat:@"%d%@%d%@%d", hours, sepString, mins, sepString, secs]
...如果我能找到一种方法可以使用本地化的sepString(时间组件分隔符)。 NSLocale似乎没有这个。
... would work if I could find a way to get at a localized "sepString" (the time component separator). NSLocale does not seem to have this.
想法?
推荐答案
以下是为任何语言环境获取时间组件分隔符的一种公认的hackish方法。它应该适用于iOS 3.2及更高版本。我知道代码可以更简洁,但我打开了maximum-verbosity标志,使其尽可能可读。
Here is a admittedly hackish way to get the time component separator for any locale. It should work on iOS 3.2 and above. I know the code can be more concise, but I turned my "maximum-verbosity" flag on to make it as readable as possible.
//------------------------------------------------------------------------------
- (NSString*)timeComponentSeparator
{
// Make a sample date (one day, one minute, two seconds)
NSDate *aDate = [NSDate dateWithTimeIntervalSinceReferenceDate:((24*60*60)+62)];
// Get the localized time string
NSDateFormatter *aFormatter = [[NSDateFormatter alloc] init];
[aFormatter setDateStyle:NSDateFormatterNoStyle];
[aFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *aTimeString = [aFormatter stringFromDate:aDate]; // Not using +localizedStringFromDate... because it is iOS 4.0+
// Get time component separator
NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@":-."];
NSRange aRange = [aTimeString rangeOfCharacterFromSet:aCharacterSet];
NSString *aTimeComponentSeparator = [aTimeString substringWithRange:aRange];
// Failsafe
if ([aTimeComponentSeparator length] != 1)
{
aTimeComponentSeparator = @":";
}
return [[aTimeComponentSeparator copy] autorelease];
}
//------------------------------------------------------------------------------
这篇关于如何定位“定时器”在iPhone上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!