-1

I want to get the date and time in a specific time zone. I am getting most of the things right but just at the end when i get the date from NSString using NSDateFormatter method it returns me the date in the GMT specific time zone. The method [formatter stringFromDate:gmtDate]; return me the expected date and time. The problem happen when i get the date from the string i-e when i execute this method self.localTime = [formatter dateFromString:str];. self.localTime is a NSDate property in my class.

So when i print the str it gives me the date and time in that specific time zone which is represented as self.timeZoneID, which is also a property on my class

        NSDate *gmtDate = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setTimeZone:[NSTimeZone timeZoneWithName:self.timeZoneID]];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *str = [formatter stringFromDate:gmtDate];
        NSLog(@"Date string : %@", str);
        self.localTime = [formatter dateFromString:str];

Any idea that what could be the reason that i am getting the right string output but when i assign it to my property localTime it give me the time in GMT

Abdul Samad
  • 5,748
  • 17
  • 56
  • 70
  • An NSDate object is GMT time. You can't change that (without breaking some rules) and you shouldn't. – Hot Licks Sep 15 '14 at 11:51
  • possible duplicate of [Set NSDate TimeZone?](http://stackoverflow.com/questions/8866515/set-nsdate-timezone) – Hot Licks Sep 15 '14 at 11:52

1 Answers1

0

Reason is that NSDate have a default time zone that is GMT for consideration and when a user wants to have time specific for some time zone then NSDateFormatter provides way to set specific time zone which you are using for gmtDate object and not for self.localTime(this is taking GMT ,default time zone).

nikhil84
  • 3,235
  • 4
  • 22
  • 43
  • So how to do this... i mean self.localTime = [NSDate date]; and then self.localTime = [formatter dateFromString:[formatter stringFromDate:self.localTime]]; i have tried this, this is also not working.... – Abdul Samad Sep 15 '14 at 09:41
  • What exactly your trying to achieve ?! – nikhil84 Sep 15 '14 at 09:49
  • I want to get the NSDate in some specific time zone. I want NSDate object not NSString object. – Abdul Samad Sep 15 '14 at 09:50
  • For specific time zone u need to apply formatter and then use the string which u get as in nsdate it takes GMT as default. Thats why nsdateformatter is there to get time as per our location time zone or in case if you want to show time according to other time zone. So better save str after using formatter. Also simply check nsdate time and GMT time(on google) then you do get it. – nikhil84 Sep 15 '14 at 10:08