0

NSDateFormatter converting into wrong date don't know why

I am converting following string 19-01-2014 01:06:54 PM into date using following code

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"DD-MM-YYYY hh:mm:ss a"];
NSDate *date = [dateFormat dateFromString:startTime];

And i am getting following output which is incorrect.Please suggest some thing

Printing description of date: 2014-01-04 07:36:54 +0000

2 Answers2

1

The "DD-MM-YYYY" part in your format string is not correct, is should be "dd-MM-yyyy". (See http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns for a full list of all date formats.)

Also you should set a "POSIX locale" to be independent of the user's locale/region settings:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];
[dateFormat setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *date = [dateFormat dateFromString:startTime];
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • You can also set a timezone and calendar *instead* of a locale, if that makes more sense. – trojanfoe Jan 19 '14 at 10:47
  • @trojanfoe: That are two different things. Setting the POSIX locale is useful if the input has a fixed *format*, compare http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature. - Setting the timezone can be done if the date itself should not be interpreted in the local timezone. I don't know if that is also an issue here. – Martin R Jan 19 '14 at 11:42
0

Printing an NSDate will return the default description -- since NSDates don't take locale, timezone, etc. into consideration, it defaults to UTC +/- 0000 (notice the +0000).

John
  • 2,675
  • 2
  • 18
  • 19