Converting Date and Time according to Local Timezone (iOS)

Posted By : Ashish Tyagi | 18-Feb-2014

Here, we are going to convert Date and Time according to Local Timezone or User current location. Server gives date and time according to their timezone but there is possibility, User timezone is different from server timezone .So in that case ,we have to convert date and time according to local timezone.

1.) First, create an NSDateFormatter to get the NSDate sent from the server.

 NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
        

2.) Convert the date string to a NSDate.

NSDate* sourceDate = [dateFormatter dateFromString:dateString];
        

3) Specify ,Local and Destination timezone in which you want to convert your date.

For getting timezone of your source date:

 NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        

For getting User timezone :

 NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

        

4.) Calculate the inverval between source timezone and user timezone as given bellow:

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    
    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
        

5.) Now, create an NSDateFormatter for formatting date in which you want to show.

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

Hope it is useful for you :)

Aashish Tyagi

[email protected]

About Author

Author Image
Ashish Tyagi

Ashish is a iPhone application developer with experience in Objective-C , Titanium and Phonegap frameworks. Ashish loves watching movies in his free time.

Request for Proposal

Name is required

Comment is required

Sending message..