我的应用程序从GMT +1(UTC / GMT +1小时)时区的远程服务器获取日期/时间。
服务器提供的格式为:
24 08 2011 08:45 PM
我想将此时间戳转换为用户时区的等效时间/日期(用户可以在世界的任何地方)。
因此作为一个例子: 应提交来自服务器的24 08 2011 08:45 PM
24 08 2011 09:45 PM给意大利用户(罗马)(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];
我将非常感谢您对此事的想法和建议
答案 0 :(得分:4)
只需在dateFormatter中设置timeZone,此代码就足够了
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:45 PM(GMT)..然后将其转换为具有本地时间的字符串,只需编写以下代码,
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSString *stringFromDAte = [dateFormatter stringFromDate:dateString];