iOS设备从12小时切换到24小时设置时出现意外行为

时间:2015-10-07 14:32:39

标签: ios objective-c nsdateformatter

我有一个使用军事时间(HH:mm)格式化的应用。当设备处于12小时时间设置时,应用程序中的时间字段是正确的。例如,下午5:00显示为17:00。当我将设备设置更改为24小时时,时间字段显示为空。我决定将应用中的格式更改为常规时间(hh:mm a)。当设备设置为12小时模式时,时间字段正确显示,例如,下午5:00。当我将设备切换到24小时模式时,时间字段再次显示为空。所以似乎无论时间格式为12小时(hh:mm a)还是军事时间(HH:mm),当设备处于24小时模式时都显示为null。 JSON数据源为"functionStartTime":"05:00 PM",它存储在Core Data中,其属性名称为startTime,类型为Date。代码如下。

NSDate * sTime = [object valueForKey:@"startTime"];
NSDateFormatter *sdf = [[NSDateFormatter alloc]init];
NSLocale *slocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[sdf setLocale:slocale];
[sdf setDateFormat:@"HH:mm"];
[sdf setTimeZone:[NSTimeZone localTimeZone]];
NSString *sTimeStr = [sdf stringFromDate:sTime];
NSLog(@"Start %@", sTimeStr);

1 个答案:

答案 0 :(得分:0)

尝试使用以下内容替换您的代码段 -

NSDate * sTime = [object valueForKey:@"startTime"];
// get the locale
[NSLocale autoupdatingCurrentLocale];
NSLocale *theLocale = [NSLocale currentLocale];

// set the formatter like this
NSDateFormatter *sdf = [[NSDateFormatter alloc] init];
    [sdf setLocale:theLocale];
    [sdf setDateStyle:NSDateFormatterNoStyle];
    [sdf setTimeStyle:NSDateFormatterShortStyle];

NSString *sTimeStr = [sdf stringFromDate:sTime];
NSLog(@"Start %@", sTimeStr);

如果用户在设置中更改时间格式12 / 24hr,您还需要一些机制来检查应用从后台返回的时间。