对于MM / dd / yyyy,NSDateFormatter dateFromString返回nil

时间:2014-04-23 21:06:00

标签: ios objective-c ios7 nsdate nsdateformatter

我在很多应用程序和函数中使用了相同的nsdateformatter样式和字符串,但是有一个函数是从后台线程调用的,当我放置断点时,我看到NSDate变为我使用nil

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

为什么日期格式化程序在上述情况下返回nil?

1 个答案:

答案 0 :(得分:2)

您使用了错误的格式化程序:

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

您需要使用detailformatter

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

您已在detailformatter上设置了正确的格式!