日期中的字符串不起作用

时间:2017-05-10 05:35:57

标签: ios objective-c xcode nsdate nsdateformatter

    -(void)viewLogAction
   {
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [formatter dateFromString:_selectedDate];
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];

NSString *convertedString = [formatter stringFromDate:date];

 _allFood = [CoreDataMethods foodLogFromCoreData:convertedString];
if([_allFood count]==0)
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"No data" message:@"Sorry, No food item to display on this date" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];

}
else{

[self performSegueWithIdentifier:@"viewLogSegue" sender:self];

}
}

这是我的代码。 NSString _selectedDate的值为2017-05-09,但行NSDate *date = [formatter dateFromString:_selectedDate];未将任何值传递给date。请帮我找出问题所在。

2 个答案:

答案 0 :(得分:1)

您发布的代码很好,如果_selectedDate不是零,则会正常运行。检查您是否正确设置_selectedDate中的值。

答案 1 :(得分:-5)

试试这个

NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [formatter dateFromString:_selectedDate];
[formatter setDateFormat:@"dd-MM-yyyy"];