2

嗨,世界专家,

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

我正在以下列方式格式化一个表示 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;
}

在全球所有当地人中一切正常。

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

示例:格式化程序 12 之前 12:00 AM 之后 格式化程序 13 之前 之后 (null)

任何想法为什么会发生这种情况?

谢谢!

4

3 回答 3

3

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

为了解决这个问题,我正在创建一个特定的语言环境,然后使用这个语言环境来表达 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 和强大的手机时代它可以工作;)

于 2012-08-08T14:35:39.683 回答
1

NSDateFormatter使用当前的语言环境和时间设置来解析(和输出)时间。如果要使用特定的时间格式,请自行设置日期格式化程序的区域设置。

dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

此外,创建日期格式化程序很昂贵,如果您经常调用此函数,您应该将日期格式化程序缓存在静态变量中。

于 2012-08-07T11:49:59.160 回答
1

我之前也遇到过这个问题。

根据您的需要,使用以下代码来格式化您的日期。

+(NSDate *)getGMTDateToView:(NSDate *) availableDate formatter:(NSDateFormatter *)timeFormat {


     NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
     [timeFormat setLocale:enUSPOSIXLocale];


     NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; 
     NSTimeInterval gmtTimeInterval = [availableDate timeIntervalSinceReferenceDate] + timeZoneOffset;

     [timeFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

     [timeFormat setDateStyle:NSDateFormatterShortStyle];
     [timeFormat setTimeStyle:NSDateFormatterShortStyle];

      enUSPOSIXLocale = nil;
      return [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];

}

我从苹果的一个文档中找到了上面的代码(我已经根据我的需要修改了(一点点)它),但现在无法找到这个链接。

于 2012-08-07T12:08:28.950 回答