将GMT时间转换为当地时间

3 iphone objective-c nsdate nstimezone ios

我目前的GMT时间 - 2013-05-15 08:55 AM

我当前的时间是 - 2013-05-15 02:06 PM 和时区是 - Asia/Kolkata

我尝试使用此代码将上述GMT转换为我当地时间

   NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"Asia/Kolkata"];
   [dateFormatter setTimeZone:sourceTimeZone];


      // timeStamp - is the above GMT time

   NSDate *dateFromString = [dateFormatter dateFromString:timeStamp];
    NSLog(@"local time is %@",dateFromString);
Run Code Online (Sandbox Code Playgroud)

但这给了我wron的时间 - 2013-05-14 19:04:00 +0000 而不是2013-05-14 02:06 PM

为什么会这样?请帮我澄清一下.谢谢

rck*_*nes 7

没有什么是错的,一个NSDate实例永远不会有时区(好吧它会,但它总是GMT,由+0000日期描述中的时区指示).

您在代码中告诉dateformatter的是您要解析的日期的时区,Asia/Kolkata但您希望它是GMT.

首先,您需要NSDate从输入日期字符串中创建一个对象,并将时区设置为正确的时区,GMT如您所示.

NSTimeZone *gmtTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:sourceTimeZone];
NSDate *dateFromString = [dateFormatter dateFromString:timeStamp];
NSLog(@"Input date as GMT: %@",dateFromString);
Run Code Online (Sandbox Code Playgroud)

然后,当您将日期作为字符串使用时:

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Kolkata"];
[dateFormatter setTimeZone:sourceTimeZone];
NSString *dateRepresentation = [dateFormatter stringFromDate:dateFromString];
NSLog(@"Date formated with local time zone: %@",dateRepresentation);
Run Code Online (Sandbox Code Playgroud)


Ans*_*Ans 5

我发现将GMT时间转换为您当地时区的最短路径是

 NSDate* localDateTime = [NSDate dateWithTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT] sinceDate:dateInGMT];
Run Code Online (Sandbox Code Playgroud)

此外,要将此日期值转换为字符串

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];//use the formatted as per your requirement. 

//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

NSString *localTimeDateString = [formatter stringFromDate:localDateTime];
Run Code Online (Sandbox Code Playgroud)