将GMT时间转换为当地时间

时间:2013-05-15 08:36:08

标签: iphone ios objective-c nsdate nstimezone

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

我目前的当地时间是 - 2013-05-15 02:06 PM 和时区是 - 亚洲/加尔各答

我尝试使用此代码将上述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);

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

为什么会这样? 请帮我清除这一点。谢谢你提前

5 个答案:

答案 0 :(得分: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);

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

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

答案 1 :(得分:5)

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

 NSDate* localDateTime = [NSDate dateWithTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT] sinceDate:dateInGMT];

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

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];

答案 2 :(得分:0)

NSLog(@"local time is %@",[dateFormatter stringFromDate: dateFromString]);

答案 3 :(得分:0)

NSTimeZone* gmtTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* localTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"Asia/Kolkata"];

NSDateFormatter *gmtDateFormatter = [[NSDateFormatter alloc] init];
[gmtDateFormatter setTimeZone:gmtTimeZone];

NSDate *date = [gmtDateFormatter dateFromString:timestamp];

NSDateFormatter *localDateFormatter = [[NSDateFormatter alloc] init];
[localDateFormatter setTimeZone:localTimeZone];

NSLog(@"local time is %@",[localDateFormatter stringFromDate:date]);

答案 4 :(得分:0)

使用 timeZoneWithName

NSDate *date=[[NSDate alloc]init];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Kolkata"]];
[timeFormat setDateFormat:@"HH:mm"];
NSString *dateStr=[timeFormat stringFromDate:date];