我在很多应用程序和函数中使用了相同的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];
为什么日期格式化程序在上述情况下返回nil?
答案 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
上设置了正确的格式!