dateFromString returns me null when I am trying to convert NSString to NSDate
here is my code:
NSString *dateString = @"Wed 16 Oct 2013";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale systemLocale]];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setDateFormat:@"EEE dd MMM yyyy"];
[dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
NSDate *myDate = [dateFormatter dateFromString: dateString];
Please, give me any suggestions about this.
It's a locale issue and it's sort of the same of NSDateFormatter Strings in iOS 7, just the other way around.
Probably in your system locale Wed
or/and Oct
are not valid valid literals for a weekday or/and a month.
Try setting the locale to en_US
or to currentLocale
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
or
NSLocale *locale = [NSLocale currentLocale];
For more formatting style http://cybersam.com/ios-dev/quick-guide-to-ios-dateformatting
NSString *dateString = @"Wed 16 Oct 2013";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"EEE dd MMM yyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSLog(@"%@", dateFromString);