Search code examples
iosobjective-cxcodensdatensdateformatter

NSDateFormatter MMM conversion


As before XCode 9 I had no issue regarding DateFormatter.

With the update I have a issue I do not seem to be able to bypass.

I am busy converting dates from NSString to NSDate, however my code seems to not be able to initialize the NSDate.

My Code:

NSString *testdate = @"Sep 20 2017  1:46PM"; // this is how my date looks

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMM dd yyyy hh:mma"]; 

NSDate *thisDate = [df dateFromString: testdate]; // this returns nil

I have tried manipulating the string in various ways, and only after I turned the function I found the dateformat issue to have appeared.

Has anyone found this issue and a possible solution?

Edit:

The only device I have this on is a iPhone 7 with iOS 11 (two different devices was tested and iPhone 7 with iOS 10 is also working correctly). I have an iPhone 6 plus as well as an iPhone 7 Plus which are both on iOS 11, and both these are working... with the time format

When I convert the [NSDate date] to string with the same date formatter my result is: M09 20 2017 1:46PM... - this was a date format issue it seems(seems to have happened when I changed the timeformat to test) and is now working however is not the problem to my issue


Solution

  • After closer investigation it seems like if I have setup a DateFormatter I also need to add a Locale to get it to work... The dates I got from a server so I can't just change it, due to being used on a website as well.

    I received the date from the server as AM/PM and the Locale solved the issue

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MMM dd yyyy hh:mma"];
    [df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    

    This solved the issue that I had.