Bharat
Bharat

Reputation: 3007

iOS convert server time to device local time?

I'm getting some issue to convert server time(argentina) to device local time. here is my current code-

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

And here is the log if sourceTime string is 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

note that i'm getting local time same as the time string i pass into the method. i looked various SO post like this and this. Any help would be appreciated.

Upvotes: 0

Views: 685

Answers (1)

Johnykutty
Johnykutty

Reputation: 12829

Since your time string is in ART, you should set the timezone of date formatter before making date from the string. Means like following

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

Upvotes: 1

Related Questions