ios - -[NSDateFormatter dateFromString :] returns nil

标签 ios objective-c cocoa-touch nsdateformatter

    NSString *lower = [NSString stringWithFormat:@"%@",[newDates objectAtIndex:0]];
    NSString *higher = [NSString stringWithFormat:@"%@",[newDates objectAtIndex:[newDates count]-1]];
    NSLog(@"%@",lower);
    NSLog(@"%@",higher);

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *dtLower = [df dateFromString:lower];

    NSDate *dtHigher = [df dateFromString:higher];
    [df release];
    NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
    [df1 setDateFormat:@"yyyy-MM-dd"];
    NSString * lowerDate = [df1 stringFromDate:dtLower];
    NSString * higherDate = [df1 stringFromDate:dtHigher];
    UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 31, self.view.frame.size.width, 30)];
    [dateLabel setTextColor:[UIColor grayColor]];
    dateLabel.text = [NSString stringWithFormat:@"%@ - %@",lowerDate,higherDate];
    [self.view addSubview:dateLabel];

控制台中 lowerhigher 的输出是:

2011-05-23 14:55:52.767 Vocab[4225:207] 2011-05-23 03:58:22
2011-05-23 14:55:53.781 Vocab[4225:207] 2011-05-23 07:14:56

这里上面的代码对我不起作用。 higherlower 的值不为空,但当我尝试使用 NSDateFormatter 将其转换为 NSDate 时,它​​返回 nil。

所以 dtLowerdtHigher 返回 nil

有什么问题吗?

最佳答案

尝试设置 [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

关于ios - -[NSDateFormatter dateFromString :] returns nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6095388/

相关文章:

ios - MKAnnotation 文本到 UILabel

ios - 使我的 UIWebView 的背景透明失败

ios - 修改容器 View 的高度

ios - Youtube YTHelper 查看视频播放暂停后自动开始

iphone - 使用按钮而不是 ui 导航 Controller 在 View 之间切换

ios - 如何将数据从 ViewController 传递到标签栏 iOS 中的 ViewController?

ios - NSURL 的 URLWithString 和 fileURLWithPath 有什么区别?

objective-c - ABRecordCopyValue() EXC_BAD_ACCESS 错误

ios - 进一步说明 "How to implement UISearchController with objective c"

iphone - 在 iPhone 项目中加载数据文件