NSDateFormatter is returning null for date in ios

2019-08-30 19:34发布

问题:

I am converting string to date and again to string. using following code

 NSString *newDate =[NSString stringWithFormat:@"%@",[(Jobs *)[tableArray objectAtIndex:indexPath.row]Date]];


    NSLog(@"New Date is %@",newDate);
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy h:mm:ss a"];
    NSDate *myDate = [dateFormat dateFromString:newDate];
    [dateFormat setDateFormat:@"MM/dd/yyyy"];

    NSString *str = [dateFormat stringFromDate:myDate];

    NSLog(@"DAte is %@",str);

It is returning date in simulator but not in iphone 4.3.3 please help

回答1:

NSDateFormatter will return nil if it can't get the date from a string. To see if it can parse the date add an other NSLog statement:

NSString *newDate =[NSString stringWithFormat:@"%@",[(Jobs *)[tableArray objectAtIndex:indexPath.row]Date]];

NSLog(@"New Date is %@",newDate);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy h:mm:ss a"];

NSDate *myDate = [dateFormat dateFromString:newDate];
NSLog(@"Date parsed: %@", myDate);

[dateFormat setDateFormat:@"MM/dd/yyyy"];

NSString *str = [dateFormat stringFromDate:myDate];

NSLog(@"DAte is %@",str);

But since you only want the firs part of the string why not just substring it.

NSString *str = [newDate substringToIndex:10];

and what is returned here:

NSString *newDate =[NSString stringWithFormat:@"%@",[(Jobs *)[tableArray objectAtIndex:indexPath.row]Date]];

it the property Date already a NSDate ?, can you show your .h file for Jobs?