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 ?

Answers


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.


Need Your Help

How to retrieve the data from database and display in pdf format in java

java mysql jsp pdf jdbc

I want to display the data which are stored in the database in a pdf file format

git rebase ate my commits ! Translate 'git reflog' output for me?

git version-control git-rebase git-reset

I had done five commits and I wanted to make them all into one commit before pushing them. For some reason I decided to try doing this by a different means than I usually use.