K2Digital
K2Digital

Reputation: 603

NSDateFormatter not returning correctly

I am parsing an XML file and I'm trying to bring it into data that I can use in my iOS App.

I have an NSMutableString called elementDate

If I read the XML file in and do….

NSLog(@"Read date: %@", elementDate):

I get

Read date: 2013-12-31

which is what I expect. But I need to now convert this to an NSDate

So I declare a dateFormatter

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [dateFormatter setCalendar:calendar];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

And then I do a

NSLog(@"Date From String: %@", [dateFormatter dateFromString:elementDate]);

The result is:

Date From String: (null)

What simple thing am I missing?

Upvotes: 0

Views: 100

Answers (1)

danh
danh

Reputation: 62686

The code runs fine. No need to set the calendar as the commenter suggests. I suspect that you've picked up some whitespace in the date string during the xml parse. Try

NSString *trimmed = [elementDate stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"Date From String: %@", [dateFormatter dateFromString:trimmed]);

Upvotes: 2

Related Questions