我的应用程序从始终处于GMT +1 (UTC/GMT +1小时)时区的远程服务器获取日期/时间。
服务器提供的格式是:
24 08 2011 08:45PM
我想把这个时间戳转换成用户所在时区的等效时间/日期(用户可以在世界上任何地方)
以为例:24 08 2011 08:45PM来自服务器应该呈现
24 08 2011 09:45PM to an Italian user (rome) (GMT + 1)
这段代码可以在某些时区工作,但我有一种不好的感觉,这是非常错误的,有一个更优雅的方式来做
NSString *dateString = @"24 08 2011 09:45PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSDate *dateFromString = [[[NSDate alloc] init] autorelease];
dateFromString = [dateFormatter dateFromString:dateString];
NSDate* sourceDate = dateFromString;
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;
NSString *thePubDate = [dateFormatter stringFromDate:destinationDate];//[appLogic getPubDate];
NSLog(@"Result : %@",thePubDate);
[dateFormatter release];
//[dateFromString release];
[destinationDate release];
非常感谢您对此事的意见和建议
只需在dateFormatter中设置时区,此代码就足够了
NSString *dateString = @"24 08 2011 09:45PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"];
[dateFormatter setTimeZone:sourceTimeZone];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
dateFromString现在将具有日期24 08 2011 08:45PM(GMT)..然后,要将其转换为具有本地时间的字符串,只需编写以下代码
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSString *stringFromDAte = [dateFormatter stringFromDate:dateString];