Search code examples
iphoneiosnsdateformattergmtnstimezone

Issue in coverting GMT time to Local time


My current Device time is --- 2013-05-09 10:23 AM

I convert it int GMT with following code

   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
   dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm a";

   NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
  [dateFormatter setTimeZone:gmt];
   NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
   NSLog(@"time in GMT ------ %@",timeStamp);

And I got the out put as

     time in GMT ------  2013-05-10 04:53 AM

then I found my time zone

  NSTimeZone *localTime = [NSTimeZone systemTimeZone];
  NSLog(@"local timezone  is------ %@",[localTime name]);

out put

  local timezone  is------ Asia/Kolkata

Now I need to convert the above GMT time to local time.I used the following code

   NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:[localTime name]];
  [dateFormatter setTimeZone:sourceTimeZone];
   NSDate *dateFromString = [dateFormatter dateFromString:timeStamp];
   NSLog(@"local time is ------- %@",dateFromString);

But I am getting a wrong out put..

   local time is ------- 2013-05-09 19:23:00 +0000

Why this happen ? I should get local time as - 2013-05-09 10:23 AM


Solution

  • // get current date/time

    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *currentTime = [dateFormatter stringFromDate:today];
    [dateFormatter release];
    NSLog(@"User's current time in their preference format:%@",currentTime);