首先,我知道这已被问过数百次,我读了大概99个问题和答案。 我的问题是我在我的应用程序中使用了时间并且我有一个设置,它允许用户覆盖实际的系统时间格式。表示如果系统使用24h格式,用户仍然可以使用该覆盖设置以12h格式显示时间。
然而,它并不总是有效,这里的情况如下:
1) System = 12h
Override off: displays 12h format
Override on (to 24h): displays 24h format
Override on (to 12h): displays 12h format
2) System = 24h
Override off: displays 24h format
Override on (to 24h): displays 24h format
Override on (to 12h): displays 24h format
似乎情况2)我无法显示12h格式: - / 而且我已经尝试过不同的事情。我从Core-Data获取设置(bool)和时间。这里是我在if语句中设置格式化程序的地方,这是我使用NSLog验证的。
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
if (use24hFormat) {
// we have to use 24h time format
[formatter setDateFormat:@"HH:mm"];
NSLog(@"We have to use 24h-Format);
} else if (!use24hFormat) {
// we have to use 12h time format
[formatter setDateFormat:@"hh:mm a"];
NSLog(@"We have to use 12h-Format);
}
任何想法?谢谢你们
输出:
I believe you, I just ran your code (on iPhone with 24h format not simulator) and it does not work :-( Here is the OUTPUT
2014-06-27 21:02:39.565 Test[687:60b] We have to use 24h-Format
2014-06-27 21:02:39.572 Test[687:60b] timeString: 21:02
2014-06-27 21:02:39.574 Test[687:60b] We have to use 12h-Format
2014-06-27 21:02:39.576 Test[687:60b] timeString: 21:02
Then I ran it on simulator (also 24h format)
[3440:60b] We have to use 24h-Format
[3440:60b] timeString: 21:05
[3440:60b] We have to use 12h-Format
[3440:60b] timeString: 9:05 PM
答案 0 :(得分:0)
编辑使用H和h提供示例:
有关日期格式代码,请参阅:Formatting Dates and Times
这是我的测试,因为@jcaron也验证了:
NSDate *date = [NSDate date]; // Where my test date is in the PM
BOOL use24hFormat;
NSString *timeString;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
use24hFormat = YES;
if (use24hFormat) {
[formatter setDateFormat:@"H:mm"];
NSLog(@"We have to use 24h-Format");
} else {
[formatter setDateFormat:@"h:mm a"];
NSLog(@"We have to use 12h-Format");
}
timeString = [formatter stringFromDate:date];
NSLog(@"timeString: %@", timeString);
use24hFormat = NO;
if (use24hFormat) {
[formatter setDateFormat:@"H:mm"];
NSLog(@"We have to use 24h-Format");
} else {
[formatter setDateFormat:@"h:mm a"];
NSLog(@"We have to use 12h-Format");
}
timeString = [formatter stringFromDate:date];
NSLog(@"timeString: %@", timeString);
NSLog输出:
我们必须使用24h格式
timeString:21:51
我们必须使用12h格式
timeString:9:51 PM
如果这对OP不起作用,则还有其他变量。