1

次のコードが一貫性​​のない時間値を返す理由を誰か説明できますか? ユーザー指定の日付/時刻文字列から NSDate オブジェクトを作成しようとすると、誤った結果が得られました。問題を説明するために、以下のコードをまとめました。

// Create two strings containing the current date and time
NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

 NSDateFormatter * timeFormat = [[NSDateFormatter alloc] init];
 [timeFormat setDateFormat:@"HH:mm:ss a"];
 timeFormat.AMSymbol = @"AM";
 timeFormat.PMSymbol = @"PM";
 timeFormat.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"EDT"];

 NSDate * now = [[NSDate alloc] init];
 NSString *theDate = [dateFormat stringFromDate:now];
 NSString *theTime = [timeFormat stringFromDate:now];

 NSLog(@"The current date/time is (GTM): %@", now);
 NSLog(@"The current date/time is (EDT): %@ %@", theDate, theTime);

 // Combine the date and time strings
 NSMutableString * theDateTime = [[NSMutableString alloc] init];
 theDateTime = [theDateTime stringByAppendingString:theDate];
 theDateTime = [theDateTime stringByAppendingString:@" "];
 theDateTime = [theDateTime stringByAppendingString:theTime];

 // Define the formatter to parse the combined date and time string
 NSDateFormatter * dateFormatter=[[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
 dateFormatter.AMSymbol = @"AM";
 dateFormatter.PMSymbol = @"PM";
 dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"EDT"];

 // Create an NSDate object using the combined date and time string
 NSDate * theDateTimeObject=[dateFormatter dateFromString:theDateTime];
 NSString * theDateTimeString=[dateFormatter stringFromDate:theDateTimeObject];

 // Print the results
 NSLog(@"theDateTimeObject (GMT) = %@", theDateTimeObject);
 NSLog(@"theDateTimeString (EDT) = %@", theDateTimeString);

このコードは、次の出力を生成します。

  The current date/time is (GMT): 2015-09-29 22:28:10 +0000
  The current date/time is (EDT): 2015-09-29 18:28:10 PM
  theDateTimeObject (GMT) = 2015-09-29 16:28:10 +0000
  theDateTimeString (EDT) = 2015-09-29 12:28:10 PM

結合された日付と時刻の文字列が日付フォーマッタによって解析されて NSDate オブジェクトが作成されると、明らかに何か問題が発生します。入力されたタイム ゾーンを理解していないようで、本来あるべき時間 (つまり +4 時間) から数時間ずれている GMT の時刻を返します。タイムゾーンを「EDT」に設定したので、入力にオフセットをハードコーディングする以外に、この問題を解決するために他に何ができるかわかりません。どんな助けでも大歓迎です。

4

1 に答える 1

2

HH12 時間形式 ( ) の代わりに24 時間形式 ( hh) を使用し、AM/PM ( ) を使用することで、悪いことをしていますa

HHフォーマットの の両方のインスタンスを に変更するhhと、期待される結果が得られるはずです。

また、フォーマッタのロケールを特別なロケールen_US_POSIXに設定して、デバイスの 24 時間制の設定に関する問題を回避する必要があります。

補足: の使用NSMutableStringはすべて間違っています。これを試して:

NSMutableString * theDateTime = [[NSMutableString alloc] init];
[theDateTime appendString:theDate];
[theDateTime appendString:@" "];
[theDateTime appendString:theTime];

または単に使用します:

NSString *theDateTime = [NSString stringWithFormat:@"%@ %@", theDate, theTime];
于 2015-09-29T23:14:52.417 に答える