GMT is showing wrong date 5 hrs. back

200 Views Asked by At

I am using this code to show date which i am getting from server but with GMT it is showing time of 5 hrs. back

-(NSString *)getDateStringFromServer:(NSDate *)date{
  NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
  [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:+0000]];
  [formatter setDateFormat:@"dd MMM yyyy h:mm a"];
  NSString *dateAsString = [formatter stringFromDate:date]; 
  return dateAsString;
}
1

There are 1 best solutions below

2
On

set time zone accordingly. as you are getting time according to gmt when you use +0000

[NSTimeZone timeZoneForSecondsFromGMT:+0000]

to get time according to your timeZone set seconds difference according to your time zone. my timezone is GMT+5 and I set +(3600*5).

[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:+(3600*5)]];

and got correct output "12 Dec 2014 7:55 PM".

which previously was "12 Dec 2014 7:55 PM" with +0000 and was wrong and 5 hrs back..

updated: as suggested by @Tom Harrington you should use local time instead of timezoneforSecondsFromGmt.

[formatter setTimeZone:[NSTimeZone localTimeZone]];