3

我得到了当前的 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);

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

为什么会发生这种情况?请帮我清除这个。在此先感谢

4

5 回答 5

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);
于 2013-05-15T08:42:13.380 回答
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];
于 2013-12-08T19:41:30.733 回答
0
NSLog(@"local time is %@",[dateFormatter stringFromDate: dateFromString]);
于 2013-05-15T08:43:13.413 回答
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]);
于 2013-05-15T08:49:29.967 回答
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];
于 2013-05-15T09:02:06.393 回答