iphone - 为什么 NSDateFormatter 在 12 小时时间设置的 24 小时本地上返回 NULL?

标签 iphone objective-c ios xcode ipad

世界各地的专家们大家好,

我遇到了一个非常奇怪的问题:

我按以下方式格式化表示 00-23 之间时间(由 Google 服务返回)的字符串:

(传入一个字符串,比如 14,应该输出 14:00 或 2:00 PM,取决于用户本地)

+(NSString *) formatTime: (NSString *)timeToBeFormatted {

   NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
   [dateFormat  setDateFormat:@"HH"];
   NSDate *date = [[NSDate alloc] init];
   date = [dateFormat dateFromString:timeToBeFormatted];  

   // Convert date object to desired output format
   [dateFormat setTimeStyle:NSDateFormatterShortStyle];

   timeToBeFormatted = [dateFormat stringFromDate:date];
   return timeToBeFormatted;
}

世界各地的所有本地人一切都运转良好。

但是,只有当用户在本地将时间格式设置为 12 小时(默认为 24​​ 小时)时,格式化程序才会仅针对 12-23 之间的值返回 NULL。我想说,这很奇怪!

示例: 在格式化程序 12 之前 中午 12:00 之后 在格式化程序 13 之前 之后(空)

有什么想法为什么会发生这种情况吗?

谢谢!

最佳答案

解决了! (受到上面答案的启发)..

为了解决这个问题,我创建了一个特定的区域设置,然后使用该区域设置来表达 stringToDate。然后我使用默认用户首选项创建另一个区域设置,并使用该区域设置编写 dateBackToString ..

+(NSString *) formatTime: (NSString *)timeToBeFormatted
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

//ADDED//
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormat setLocale:enUSPOSIXLocale];

[dateFormat  setDateFormat:@"HH"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormat dateFromString:timeToBeFormatted];  

//ADDED//
NSLocale *defualtLocale = [[NSLocale alloc] init];
[dateFormat setLocale:defualtLocale];

[dateFormat setTimeStyle:NSDateFormatterShortStyle];
timeToBeFormatted = [dateFormat stringFromDate:date];  

return timeToBeFormatted;
}

我猜它对于旧设备来说相当昂贵,但在 ARC 和强大的手机时代它可以工作;)

关于iphone - 为什么 NSDateFormatter 在 12 小时时间设置的 24 小时本地上返回 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11845276/

相关文章:

objective-c - 返回参数对象时,ARC发生内存泄漏

iphone - GDataXml 和命名空间

iphone - 使用 Xcode 实现向后兼容的目标 iOS 级别

iOS 状态栏忽略根 Controller 中的 supportedInterfaceOrientations

ios - 如何检测 View Controller 的方向

iphone - 拖动时为 UIView 制作动画

iphone - UISearchBar 在 UITableView 滚动时滚动

iphone - Cocos2D 复杂动画

ios - 隐藏标签栏容器 View

iphone - 产品上的 Whatsapp 链接?