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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.