Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 661
ahmad Avatar asked Sep 13 '26 05:09

ahmad


1 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.

like image 192
Sergey Kalinichenko Avatar answered Sep 14 '26 17:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!