2011-08-24 52 views
1

我的应用程序从远程服务器获取日期/时间,该日期/时间总是在GMT + 1(UTC/GMT + 1小时)时区内。日期/时间转换为用户的本地时间 - 问题

服务器提供的格式是:

24 08 2011下午8点45分

我想这个时间戳转换为用户时区的等效时间/日期(用户可以在世界任何地方)。

从而作为一个例子: 24 08 2011下午8点45来自服务器应提交

24 08 2011下午9点45分对意大利用户(罗马)(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]; 

我会感谢对此事

您的想法和建议

回答

4

只需设置时区的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下午8点45(北京时间)。然后将其转换为字符串当地时间刚代码如下,

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"]; 
NSString *stringFromDAte = [dateFormatter stringFromDate:dateString]; 
+0

上述工作,但它会更清晰,如果两个示例代码集一起工作,你有重复的变量名称和一些变量名称不匹配。 –

相关问题