prince
prince

Reputation: 944

Calculate date and time corresponding to different timezone

I have an ipad application that draws a graph with time on y-axis. Now my problem is that, this same graph by a user can be accessed anywhere in the world. But then the time on the graph should be adjusted so that it should correspond to the current timezone of the user. So the time on the graph should compensate for any difference in time between timezones. Can anyone tell me how to take the timezone from current device and calculate the offset time if i am passing the timezone of the device from which the graph is sent.

This is my date formatting function. I intend to pass the timezone also along with the date.

+(NSDate *)DateUKFormatFromString:(NSString *)date
{
  NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init] ;
  NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
  [dateFormatter setLocale:locale];
  [dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
  NSDate* returnDate = [dateFormatter dateFromString:date];    
  return returnDate;
}

Thanks in advance.

Upvotes: 0

Views: 180

Answers (2)

prince
prince

Reputation: 944

+(NSDate *)DateUKFormatMonthFromString:(NSString *)date AndTimeZoneName:(NSString *) timeZoneName
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:timeZoneName];
[formatter setTimeZone:timeZone];
NSDate *date1 = [formatter dateFromString:date];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
return date1; 
}

In the end, this worked for me... Seems that iOS will take care of time zone differences on its own...!!!

Upvotes: 0

devluv
devluv

Reputation: 2017

there is a dateFormatter instance method setTimeZone: use it like this

[NSTimeZone resetSystemTimeZone];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

For information on the two methods, please read documentation. Hope it helps. Cheers

Edit:

If date coming from server is for a specific time Zone (time zone of the server). Then you will need to get the timeZone

NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:"Server timezone name"];
NSInteger serverDifference = [timeZone secondsFromGMT];

[NSTimeZone resetSystemTimeZone];
NSTimeZone *systemTimeZone = [NSTimeZone systemTimeZone];
NSInteger systemDifference = [systemTimeZone secondsFromGMT];

NSInteger difference = systemDifference - serverDifference;
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:difference]];

try this in case you are not getting a 0 GMT difference time from server.

Upvotes: 3

Related Questions