Want NSDateformatter for January,2000 or January 2

2020-05-06 01:02发布

问题:

I have a date January 2012. I need a NSDateFormatter for such date.

Here's my code...

//Array of Date-formatter Strings
NSArray *dateFormatterList = [
    NSArray arrayWithObjects:
        @"yyyy-MM-dd'T'HH:mm:ss'Z'", 
        @"yyyy-MM-dd'T'HH:mm:ssZ",
        @"yyyy-MM-dd'T'HH:mm:ss", @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
        @"yyyy-MM-dd'T'HH:mm:ss.SSSZ", @"yyyy-MM-dd HH:mm:ss",
        @"MM/dd/yyyy HH:mm:ss", @"MM/dd/yyyy'T'HH:mm:ss.SSS'Z'",
        @"MM/dd/yyyy'T'HH:mm:ss.SSSZ", @"MM/dd/yyyy'T'HH:mm:ss.SSS",
        @"MM/dd/yyyy'T'HH:mm:ssZ", @"MM/dd/yyyy'T'HH:mm:ss",
        @"yyyy:MM:dd HH:mm:ss", @"yyyyMMdd", @"dd-MM-yyyy",
        @"dd/MM/yyyy", @"yyyy-MM-dd", @"yyyy/MM/dd",
        @"dd MMMM yyyy", @"MMddyyyy", @"MM/dd/yyyy", 
        @"MM-dd-yyyy",@"d'st' MMMM yyyy",
        @"d'nd' MMMM yyyy", @"d'rd' MMMM yyyy",
        @"d'th' MMMM yyyy", @"d'st' MMM yyyy",
        @"d'nd' MMM yyyy", @"d'rd' MMM yyyy",
        @"d'th' MMM yyyy", @"d'st' MMMM",
        @"d'nd' MMMM", @"d'rd' MMMM",
        @"d'th' MMMM", @"d'st' MMM",
        @"d'nd' MMM", @"d'rd' MMM",
        @"d'th' MMM",@"MMMM yyyy",nil];

NSString *targetDateFormatString  = @"dd-MM-yyyy";

count++; 

if (resultString) {
    for (NSString *dateFormatterString in dateFormatterList) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:dateFormatterString];
        NSDate *originalDate = [dateFormatter dateFromString:resultString];

        if (originalDate) {
            [dateFormatter setDateFormat:targetDateFormatString];
            myDateString = [dateFormatter stringFromDate:originalDate];
            [finalDateArray addObject:myDateString];
            //NSLog(@"Converted date String is %@", myDateString);
            break;
        }
    }
}

回答1:

For January, 2000

try,

@"MMMM, yyyy"

and For January 2000

try

@"MMMM yyyy"

I have updated my answer to your other questions with this as well, Please check my answer in this link

Update:

In the above code in question set resultString = @"January 2000" and try again. I am getting it as "01-01-2000". I have updated my other answer to your question to make it as a method. Use that method and call it as, [self dateStringFromString:@"January 2000" destinationFormat:@"dd-MM-yyyy"]. Please note that since date param is not present in your original string, you will see 01 as the default date.