0

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.

Community
  • 1
  • 1
Bharat
  • 2,987
  • 2
  • 32
  • 48
  • Why declare the dateformatter as static when you are creating a new instance every time you call this method? At you issue is with the time zone. – rckoenes Sep 28 '15 at 09:18
  • because i'm calling this method in loop and don' want to recreate every time when my date formate would be same for all iteration. Is this a problem? – Bharat Sep 28 '15 at 09:21
  • 1
    But you are creating the date formatter every time. – rckoenes Sep 28 '15 at 09:22
  • 1
    To make use of this static thing you could do it like static NSDateFormatter* df = nil; if (df == nil) { df = [[NSDateFormatter alloc]init];} – Johnykutty Sep 28 '15 at 09:25
  • Ok, my fault. but removing static doesn't make any difference. – Bharat Sep 28 '15 at 09:25

1 Answers1

1

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];
}
Johnykutty
  • 12,091
  • 13
  • 59
  • 100