我正在从远程服务器检索某些日期。不幸的是可能的格式之一就是H:MM:数据的将时区:分钟:时区转换为另一个时区中的完整日期
实施例I昨天月,21,2013下载了:
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 [email protected]"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);
输出
虽然昨天的代码似乎正常工作,因为当我做了测试,我仍然在6小时的时间跨度,让我在同一天,5月21日,今天早上我发现它没有。问题在于创建正确的日期。
1)下午4点36 EDT ----> /05/2013 22点36分○○秒CEST
正确的输出应该已经/05/2013 22点36 CEST
2)下午11点51 EDT ----> /05/2013五点51分00秒CEST
正确的输出应该已经/05/2013 - 05:51 CEST
什么是处理这种特殊情况的最佳代码?
感谢
尼古拉
在获得当天的日期组件之后,为什么不给它添加时间值?您应该尝试使用UTC工作,然后在末尾应用您的时区以进行显示。 – Wain