user3116050
user3116050

Reputation: 11

iPhone: convert GMT to local time

When i convert the time from my Xcode iPhone simulator my code working fine and the output as it showing here:

2014-02-12 18:11:52 +0000

Local Time Zone (Europe/London (GMT) offset 0)

0

but when i try using my app on my iPhone 5 the output changed to

1970-01-01 12:00:00 am +0000

Local Time Zone (Europe/London (GMT) offset 0)

0

i am using xcode 5.0 and iOS 7

-(NSDate *)convertGMTtoLocal:(NSString *)gmtDateStr {

    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSTimeZone *gmt = [NSTimeZone systemTimeZone];

    [formatter setTimeZone:gmt];

    NSDate *GMTTime = [formatter dateFromString:gmtDateStr];

    NSTimeZone *tz = [NSTimeZone localTimeZone];
    NSLog(@"%@",tz);
    NSInteger seconds = [tz secondsFromGMTForDate: GMTTime];
    NSLog(@"%ld",(long)seconds);
    NSLog(@"%@",[NSDate dateWithTimeInterval: seconds sinceDate: GMTTime]);
    return [NSDate dateWithTimeInterval: seconds sinceDate: GMTTime];

}

Thanks,

Upvotes: 1

Views: 2112

Answers (2)

Krunal
Krunal

Reputation: 79776

May this extension would be easier.

Swift 4: UTC/GMT ⟺ Local (Current/System)

extension Date {

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

}


// Try it
let utcDate = Date().toGlobalTime()
let localDate = utcDate.toLocalTime()

print("utcDate - (utcDate)")
print("localDate - (localDate)")

Upvotes: 0

Duncan C
Duncan C

Reputation: 131511

NSLog logs dates in GMT. Don't use that. Create a date formatter and use that to log your date. The other poster's code is exactly backwards, and will convert the date TO GMT. Leave off the setTimeZone call in vborra's code and it should give you the date in local time.

The code might look like this:

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateStyle:NSDateFormatterNoStyle];
  [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
  NSString *time = [dateFormatter stringFromDate:[NSDate date]];
  NSLog(@"Time is %@", time);

Upvotes: 1

Related Questions