Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: convert UTC timezone to device local timezone

I am trying to convert the following timezone to device local timezone:

2013-08-03T05:38:39.590Z

Please let me know how to convert it to local timezone.

How do I do it?

like image 266
z22 Avatar asked Aug 03 '13 06:08

z22


2 Answers

Time zones can be applied to NSDateFormatter, from which you can generate NSDate variables differentiated by the time difference.

NSString* input = @"2013-08-03T05:38:39.590Z";
NSString* format = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

// Set up an NSDateFormatter for UTC time zone
NSDateFormatter* formatterUtc = [[NSDateFormatter alloc] init];
[formatterUtc setDateFormat:format];
[formatterUtc setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

// Cast the input string to NSDate
NSDate* utcDate = [formatterUtc dateFromString:input];

// Set up an NSDateFormatter for the device's local time zone
NSDateFormatter* formatterLocal = [[NSDateFormatter alloc] init];
[formatterLocal setDateFormat:format];
[formatterLocal setTimeZone:[NSTimeZone localTimeZone]];

// Create local NSDate with time zone difference
NSDate* localDate = [formatterUtc dateFromString:[formatterLocal stringFromDate:utcDate]];

NSLog(@"utc:   %@", utcDate);
NSLog(@"local: %@", localDate);

[formatterUtc release];
[formatterLocal release];
like image 126
Chris Schiffhauer Avatar answered Oct 06 '22 01:10

Chris Schiffhauer


Try like this:

   NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
   [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
   [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
   NSDate* utcTime = [dateFormatter dateFromString:@"2013-08-03T05:38:39.590Z"];
   NSLog(@"UTC time: %@", utcTime);

   [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
   [dateFormatter setDateFormat:@"M/d/yy 'at' h:mma"];
   NSString* localTime = [dateFormatter stringFromDate:utcTime];
   NSLog(@"localTime:%@", localTime);  

Hope it helps you....

like image 34
iSpark Avatar answered Oct 05 '22 23:10

iSpark