通过XML解析设置NSDate属性后使用NSDateFormatter时的NULL值

时间:2010-04-14 09:46:06

标签: iphone null nsdate nsdateformatter

我正在使用以下代码尝试在表格单元格中显示。

TimeSlot *timeSlot = [timeSlots objectAtIndex:indexPath.row];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];
NSLog(@"Time: %@", timeSlot.time);
NSDate *mydate = timeSlot.time;
NSLog(@"Time: %@", mydate);
NSString *theTime = [timeFormat stringFromDate:mydate];
NSLog(@"Time: %@", theTime);

日志输出为:

  • 2010-04-14 10:23:54.626 MyApp [1080:207]时间:2010-04-14T10:23:54
  • 2010-04-14 10:23:54.627 MyApp [1080:207]时间:2010-04-14T10:23:54
  • 2010-04-14 10:23:54.627 MyApp [1080:207]时间:( null)

我是开发iPhone的新手,因为它编译时没有任何错误或警告我不知道为什么我在日志中得到NULL。这段代码有什么问题吗?

由于

更多信息

我使用了你的答案lugte098中的代码只是为了检查我得到的日期让我相信我的TimeSlot类不能在其NSDate属性中正确设置日期。所以我的问题变成了 - 我如何从XML设置NSDate属性?

我有这段代码(缩写):

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *) string {
 if ([currentElement isEqualToString:@"Time"]) {
  currentTimeSlot.time = string
 }
}

由于

3 个答案:

答案 0 :(得分:3)

根据编辑过的问题:

您正在将XML中的字符串设置为timeSlot对象。 NSDateFormatter期望提供格式NSDate,这就是原始问题失败的原因。

所以你问第二个问题,即如何从NSString创建一个NSDate。查看文档,您可以使用dateFromString:getObjectValue:forString:range:error:getObjectValue:forString:errorDescription:。因此:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
currentTimeSlot.time = [df dateFomString:string];

如果它是nil,你应该使用错误返回方法之一。

答案 1 :(得分:0)

这可能会有所帮助:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

答案 2 :(得分:-2)

你需要设置

[timeFormat setDateFormat:@"dd MMMM YYYY"];

之前

NSString *theTime = [timeFormat stringFromDate:mydate];

这一行