1

I have a problem using NSDateFormatter in iPhone programming. Below is my code snippet.

NSString *inputDate = @"2011-03-14";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *entryDate = [formatter dateFromString:inputDate];
[formatter release]

The result I am getting is

2011-03-13 16:00:00 +0000

which is the GMT equivalent of 2011-03-14 00:00:00. (My time zone is GMT +08:00)

Why I am getting this? How to get 2011-03-14 00:00:00 as the result?

Thanks.

~Jan

Jan
  • 11
  • 1

3 Answers3

2

You can set the timezone using

[formatter setTimeZone:...]

. Alternatively I would try to just set the formatter's locale by

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"..."];
[formatter setLocale:locale];
hennes
  • 9,147
  • 4
  • 43
  • 63
  • Thanks for the response. I tried both, but the result was similar. Furthermore my formatter's timezone and locale are correctly set to the local settings by default. – Jan Mar 16 '11 at 07:59
0

Pls take a look at this

NSDateFormatter returns unexpected results

This is what Apple recommends

Community
  • 1
  • 1
visakh7
  • 26,380
  • 8
  • 55
  • 69
  • Thanks for the response. But, setting the time zone of the formatters does not seem to fix the problem. I have tried that, but the answer was the same. – Jan Mar 16 '11 at 08:13
0

You can try to add the timezone to your original string

NSString *inputDate = @"2011-03-14+0800";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-ddZZZ"];
NSDate *entryDate = [formatter dateFromString:inputDate];
[formatter release]
HyLian
  • 4,999
  • 5
  • 33
  • 40