リモートサーバーからいくつかの日付を取得しています。残念ながら、可能な形式の 1 つは単に h:mm:a です。
昨日 2013 年 5 月 21 日にダウンロードしたデータの例:
1) 午後 4 時 36 分 (EDT)
2) 午後 11 時 51 分 (EDT)
データ サーバーの TimeZone は "America/New_York" です。
私のデータ TimeZone は「ヨーロッパ/ローマ」です。
これは私が書いたコードで、今朝の午前 5 時まではうまくいくと思っていました。
NSDate *myDate = @"04:36PM EDT"; //11:51PM EDT (I know the date is May, 21 2013 but it is not in the data!)
NSArray *component = [mydate componentsSeparatedByString:@" "];
//Remove any reference to the TimeZone
//set it in the dateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat =@"MM dd yyyy h:mma";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
dateFormatter.timeZone = [[NSTimeZone alloc] initWithName:@"America/New_York"];
//Create a valid date for the hour
NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
NSDate *dateObject = [self.dateFormatter dateFromString: [NSString stringWithFormat:@"%u %u %u %@",
dateComponents.month,
dateComponents.day,
dateComponents.year,
[component objectAtIndex:0]]];
//Convert to local timeZone
dateFormatter.timeZone = [NSTimeZone localTimeZone]; // @"Europe/Rome"
dateFormatter.dateStyle = NSDateFormatterShortStyle;
dateFormatter.timeStyle = NSDateFormatterLongStyle;
NSString *localTimeZoneDate = dateFormatter stringFromDate:[dateObject];
NSLog(@"Local Time Zone Date = %@", localTimeZoneDate);
出力
昨日、コードは正常に動作しているように見えましたが、テストを行ったとき、同じ日である 5 月 21 日の 6 時間のタイムスパンにまだいたため、今朝は動作していないことがわかりました。問題は正しい日付の作成にあります。
1) 04:36PM EDT ----> 22 /05/2013 22:36:00 CEST
正しい出力は21 /05/2013 22:36 CESTであるはずです
2) 午後 11 時 51 分 (EDT) ----> 23 /05/2013 05:51:00 CEST
正しい出力は22 /05/2013 05:51 CESTであるはずです
この特殊なケースを処理するのに最適なコードは何でしょうか?
ありがとう
ニコラ