次のコードが一貫性のない時間値を返す理由を誰か説明できますか? ユーザー指定の日付/時刻文字列から 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」に設定したので、入力にオフセットをハードコーディングする以外に、この問題を解決するために他に何ができるかわかりません。どんな助けでも大歓迎です。