【问题标题】:iOS convert server time to device local time?iOS将服务器时间转换为设备本地时间?
【发布时间】: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 帖子,例如 thisthis。 任何帮助将不胜感激。

【问题讨论】:

  • 为什么每次调用这个方法都在创建一个新实例时,将 dateformatter 声明为静态?你的问题是时区。
  • 因为我在循环中调用此方法并且不想在每次我的日期格式对于所有迭代都相同时重新创建。这是个问题吗?
  • 但是您每次都在创建日期格式化程序。
  • 要使用这个静态的东西,你可以像 static NSDateFormatter* df = nil; if (df == nil) { df = [[NSDateFormatter alloc]init];}
  • 好吧,我的错。但去除静电没有任何区别。

标签: ios objective-c datetime nsdateformatter


【解决方案1】:

由于您的时间字符串在 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];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 2010-09-24
    • 2011-02-12
    • 1970-01-01
    • 2013-03-23
    • 2014-03-17
    • 2013-04-26
    • 2012-01-26
    相关资源
    最近更新 更多