[英]iOS convert server time to device local time?
我在將服務器時間(阿根廷)轉換為設備本地時間時遇到了一些問題。 這是我當前的代碼-
-(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
由於您的時間字符串位於ART中,因此您應先設置日期格式程序的時區,然后再從字符串中確定日期。 像下面這樣
-(NSString *)getLocalTimeStringFrom:(NSString *)sourceTime
{
static NSDateFormatter* df = nil;
if (!df) {
df = [[NSDateFormatter alloc]init];
df.dateFormat = @"HH:mm:ss";
}
NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:@"ART"];
[df setTimeZone: sourceZone];
NSDate *ds = [df dateFromString:sourceTime];
NSLog(@"sourceZone time is %@" , [df stringFromDate: ds]);
NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
[df setTimeZone: localTimeZone];
NSLog(@"local time is %@" , [df stringFromDate: ds]);
return [df stringFromDate: d];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.