ahmad
ahmad

Reputation: 1252

formatting NSDate object changes the time zone

I get the current NSDate in the user time zone with the following code

-(NSDate *)getCurrentDateinLocalTimeZone
{
NSDate* sourceDate = [NSDate date];

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

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;

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

return   [dateFormatter dateFromString: [dateFormatter stringFromDate:destinationDate]];
}

and at some other point in my app i want to format the date as "HH:mm" for UI purposes so i use the following method

-(NSString *)formatDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateFormat = @"HH:mm";
return [dateFormatter stringFromDate:date]; 
}

if the output of the second method is shifted by 3 hours from the result of the 1st method ,,, i only want to change the format of NSDate not the time , what am i doing wrong ?

Upvotes: 3

Views: 5318

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

The getCurrentDateinLocalTimeZone method adjusts the date for the time zone, formats it using a format string that chops off the time zone, and parses the formatted string back. The resulting NSDate is in the UTC time zone (the +0000 in 2012-07-15 16:28:23 +0000 indicates UTC time). The formatDate: method uses dateFormatter that is set up for the local time zone, producing a different time. You should set the formatter to use UTC to get the correct time: replace

[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

with

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

in the formatDate: method.

Upvotes: 6

Related Questions