NSDateFormatter is returning null for date in ios 4.3.3

我与影子孤独终老i 提交于 2020-01-17 05:10:49

问题


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?



来源:https://stackoverflow.com/questions/7386446/nsdateformatter-is-returning-null-for-date-in-ios-4-3-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!