我正在使用以下代码尝试在表格单元格中显示。
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);
日志输出为:
我是开发iPhone的新手,因为它编译时没有任何错误或警告我不知道为什么我在日志中得到NULL。这段代码有什么问题吗?
由于
更多信息
我使用了你的答案lugte098中的代码只是为了检查我得到的日期让我相信我的TimeSlot类不能在其NSDate属性中正确设置日期。所以我的问题变成了 - 我如何从XML设置NSDate属性?
我有这段代码(缩写):
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *) string {
if ([currentElement isEqualToString:@"Time"]) {
currentTimeSlot.time = string
}
}
由于
答案 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];
这一行