Jan 8, 2013

Get GMT in iOS using NSTimezone

Posted Jan 8, 2013
There are cases that you want to get the GMT string of an iPhone / iPad device. Here's how you can do it:

  NSTimeZone *localTime = [NSTimeZone systemTimeZone];
  CGFloat gmt = ([localTime secondsFromGMT]/60.f/60.f);
  
  NSMutableString *gmtStr = [[[NSMutableString alloc] init] autorelease];
  int hours;
  if (gmt < 0) {
    hours = ceil(gmt);
  } else {
    hours = floor(gmt);
  }
  
  int minutes = abs(round((gmt - hours) * 60));
  
  if (gmt >= 0) {
    [gmtStr appendFormat:@"+%d",hours];
  } else {
    [gmtStr appendFormat:@"%d",hours];
  }
  
  if (minutes > 0) {
    [gmtStr appendFormat:@":%02d", minutes];
  }
  
  NSLog(@"GMT is %@", gmtStr);

No comments:

Post a Comment