1
NSString *dateString = [[items objectAtIndex:indexPath.row] objectForKey:@"date"];
NSLog(@"DATE: %@",dateString);
// outputs 16/10 23:59:49

NSDateFormatter *dateFormat;
[dateFormat setDateFormat:@"dd/MM HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateString];

NSLog(@"DATE: %@", date);
// outputs null

但它每次都输出null。请你能帮我做错什么吗?

4

3 回答 3

0

您忘记创建NSDateFormatter

您应该替换行:

NSDateFormatter *dateFormat;

和:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
于 2012-10-16T08:26:20.443 回答
0

您必须设置年份,否则日期将显示为空。您可以使用当前年份并将您的字符串分成月份和日期,然后像这样"dd-MM-yyyy"或您想要的任何其他方式进行设置。

 NSString *string = @"16/10 23:59:49";
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];

    NSArray *arrayDateData = [string componentsSeparatedByString:@"/"];
     NSString *dayStr =[arrayDateData objectAtIndex:0];
    NSString *string1 =[arrayDateData objectAtIndex:1];
    NSString *monStr = [[string1 componentsSeparatedByString:@" "] objectAtIndex:0];

    NSString *timeString;
    timeString=[NSString stringWithFormat:@"%d-%@-%@",2012,monStr,dayStr];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString=[df dateFromString:timeString];
    NSLog(@"date from string: %@",dateFromString);

我想这会对你有所帮助。

于 2012-10-16T09:10:04.977 回答
0

你需要创建

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

于 2012-10-16T08:37:16.247 回答