开发者

Stripping the 12 Hour clock suffix from an NSString

开发者 https://www.devze.com 2022-12-17 10:16 出处:网络
I have a shortage of screen real estate for my time labels in my iPhone app. My solution is to have the time e.g. 12:00 on one line and then if the users current locale specifies that an AM-PM is used

I have a shortage of screen real estate for my time labels in my iPhone app. My solution is to have the time e.g. 12:00 on one line and then if the users current locale specifies that an AM-PM is used, have these in a second label below it.

Since AM-PM also have localized variants I can't just look for the letters "AM" or "PM", then I thought about stripping the last two letters, but by checking I found out some languages uses a format like this: "F.开发者_如何转开发M." "E.M". My next thought was to strip everything after the first 5 digits(12:34), but for hour intervals below 10 that is no good either.

Is there a "locale safe" way of always removing the localized suffix and move it to a new string, regardless of the users settings?

Thank you in advance:)


There is no locale safe way of doing that.

Use NSDateFormatter to generate two strings.

NSDateFormatter  *timeOfDayFormatter = [[[NSDateFormatter alloc] init] retain];
[timeOfDayFormatter setDateFormat:@"hh:mm"];

NSDateFormatter  *amPmFormatter = [[[NSDateFormatter alloc] init] retain];
[amPmFormatter setDateFormat:@"aa"];


NSLog(@"Time is: %@ %@",
    [timeOfDayFormatter stringFromDate:theDate],
    [amPmFormatter stringFromDate:theDate]);

Now you can layout your user interface with the two strings.

The 24-hour format is standard where I live. I'd "force" that format on the user if screen real estate is a real problem.


I ended up solving it like this and then manually test it with 15+ locale settings:

NSArray *timeParts = [NSArray arrayWithArray:[[timeFormatter stringFromDate:myDate] componentsSeparatedByString:@" "]];

Then I test the timeParts array:

if ([timeParts count] > 1) {...}

If the count is 1 it is a locale without the suffix and I don't set the "AM/PM" label. Else, I set both labels, the timeLable with [timeParts objectAtIndex:0] and the localeLabel with [timeParts objectAtIndex:1]

This seems to be a stable solution for all locales.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号