-2

I have been using same nsdateformatter style and string in a lot of apps and functions but there is one function that is called from a background thread, and when I put break points I see NSDate becomes nil when I use datefromstring

   NSString *start=[dataDict objectForKey:@"start_date"];
    NSString *end;
    if (![[dataDict objectForKey:@"end_date"] isEqualToString:@""]) {
        end=[dataDict objectForKey:@"end_date"];
    }
    else
    {
        end=[dataDict objectForKey:@"estimate_end_date"];
    }

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy"];

//    NSLocale *enUSPOSIXLocale = [[NSLocale alloc]
//                                  initWithLocaleIdentifier:@"en_US_POSIX"] ;
//    assert(enUSPOSIXLocale != nil);
//    [formatter setLocale:enUSPOSIXLocale];
//    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSDateFormatter *detailformatter = [[NSDateFormatter alloc] init];
    [detailformatter setDateFormat:@"MM/dd/yyyy"];

    NSDateComponents *dateComponents = [NSDateComponents new];
    dateComponents.year = year;
    NSDate *newDate = [[NSCalendar currentCalendar]dateByAddingComponents:dateComponents
                                                                   toDate: _earliestDate
                                                                  options:0];

    NSString *plaincurrentYearString =[formatter stringFromDate:newDate];
    NSDate *plaincurrentYearDate=[formatter dateFromString:plaincurrentYearString];

    NSDate *startDatePlain=[formatter dateFromString:start];
    NSDate *endDatePlain=[formatter dateFromString:end];

enter image description here

Why date formatter returns nil in above case?

Mord Fustang
  • 1,523
  • 4
  • 40
  • 71
  • http://stackoverflow.com/questions/4258266/nsdateformatter-datefromstring-returns-nil – meda Apr 23 '14 at 21:09

1 Answers1

2

You're using the wrong formatter:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
NSDate *startDatePlain=[formatter dateFromString:start];
NSDate *endDatePlain=[formatter dateFromString:end];

You need to use your detailformatter:

NSDateFormatter *detailformatter = [[NSDateFormatter alloc] init];
[detailformatter setDateFormat:@"MM/dd/yyyy"];
NSDate *startDatePlain=[detailformatter dateFromString:start];
NSDate *endDatePlain=[detailformatter dateFromString:end];

You've got the correct format set on detailformatter!

Rich
  • 8,108
  • 5
  • 46
  • 59