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 時間であるローカルでユーザーが 12 時間に TIME フォーマットを設定している場合にのみ、フォーマッタは 12 ~ 23 の間の値に対してのみ NULL を返します。

例: before formatter 12 after 12:00 AM before formatter 13 after (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

私もしばらく前にこの問題に直面していました。

次のコードを使用して、必要に応じて日付をフォーマットします。

+(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];

}

アップルのドキュメントの1つから上記のコードを見つけました(必要に応じて(少し)変更しました)が、現在このリンクを見つけることができません。

于 2012-08-07T12:08:28.950 に答える
1

NSDateFormatter時刻の解析 (および出力) に現在のロケールと時刻の設定を使用します。特定の時刻形式を使用する場合は、日付フォーマッタのロケールを自分で設定してください。

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

また、日付フォーマッタの作成にはコストがかかります。この関数を頻繁に呼び出す場合は、日付フォーマッタを静的変数にキャッシュする必要があります。

于 2012-08-07T11:49:59.160 に答える