【发布时间】:2015-09-28 09:16:20
【问题描述】:
我在将服务器时间(阿根廷)转换为设备本地时间时遇到了一些问题。 这是我当前的代码-
-(NSString *)getLocalTimeStringFrom:(NSString *)sourceTime
{
static NSDateFormatter* df = nil;
if (df == nil)
{
df = [[NSDateFormatter alloc]init];
}
df.dateFormat = @"HH:mm:ss";
NSDate* d = [df dateFromString:sourceTime];
NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:@"ART"];//America/Argentina/Buenos_Aires (GMT-3)
NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone]; //Asia/Kolkata (IST)
[df setTimeZone: sourceZone];
NSLog(@"sourceZone time is %@" , [df stringFromDate: d]);
[df setTimeZone: localTimeZone];
NSLog(@"local time is %@" , [df stringFromDate: d]);
NSLog(@"original time string was %@" , sourceTime);
return [df stringFromDate: d];
}
如果sourceTime 字符串是00:05:00,这是日志
2015-09-28 15:04:24.118 DeviceP[230:17733] sourceZone time is 15:35:00
2015-09-28 15:04:24.121 DeviceP[230:17733] local time is 00:05:00
2015-09-28 15:04:33.029 DeviceP[230:17733] original time string was 00:05:00
请注意,我得到的本地时间与我传递给方法的时间字符串相同。 我查看了各种 SO 帖子,例如 this 和 this。 任何帮助将不胜感激。
【问题讨论】:
-
为什么每次调用这个方法都在创建一个新实例时,将 dateformatter 声明为静态?你的问题是时区。
-
因为我在循环中调用此方法并且不想在每次我的日期格式对于所有迭代都相同时重新创建。这是个问题吗?
-
但是您每次都在创建日期格式化程序。
-
要使用这个静态的东西,你可以像 static NSDateFormatter* df = nil; if (df == nil) { df = [[NSDateFormatter alloc]init];}
-
好吧,我的错。但去除静电没有任何区别。
标签: ios objective-c datetime nsdateformatter