如何在iphone中以12小时格式显示时间

时间:2012-03-27 13:34:15

标签: iphone objective-c xcode4

每当用户在24小时格式中添加记录作为创建日期时间存储在数据库中的某些细节时,我正在开发应用程序。但为了显示目的,我以12小时格式显示时间。即我使用“dd-MMM-yyyy hh:mm a”格式显示时间并在屏幕上正确显示,但问题是用户在设置中将日期/时间格式从12小时更改为24小时格式。我的应用程序开始以24小时格式显示时间。任何人都可以帮助我,即使用户在设置中将设置更改为24小时格式。时间格式不应在12到24小时之间变化。

3 个答案:

答案 0 :(得分:2)

通常,您应该允许用户选择他们想要如何显示它。

使用您的代码,您应该可以执行此操作:

dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLocale *twelveHourLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
dateFormat.locale = twelveHourLocale;
CreatedDate = [dateFormat dateFromString:[NSString stringWithFormat:@"%@",[serviceAntInstance.arr_CreatedDate objectAtIndex:indexPath.row]]];
[dateFormat setDateFormat:@"dd-MMM-yyyy hh:mm a"];
createdDateConvert = [dateFormat stringFromDate:CreatedDate];

答案 1 :(得分:2)

请查看:

NSDateFormatter *formatterTemp = [[NSDateFormatter alloc] init];
[formatterTemp setLocale:[NSLocale currentLocale]];
[formatterTemp setDateStyle:NSDateFormatterNoStyle];
[formatterTemp setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSString *dateString = [formatter stringFromDate:[NSDate date]];

NSRange amRange = [dateString rangeOfString:[formatterTemp AMSymbol]];
NSRange pmRange = [dateString rangeOfString:[formatterTemp PMSymbol]];
BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
[formatterTemp release];
NSLog(@"%@\n",(is24h ? @"YES" : @"NO"));

答案 2 :(得分:1)

如何利用现有的语言环境?

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setLocale: locale];
[formatter setTimeStyle: NSDateFormatterShortStyle];

NSString *result = [formatter stringFromDate: [NSDate date]];

[formatter release];
[locale release];
相关问题