我有一些简单的代码应该转换我从CoreData检索的NSDate。由于某些原因,当相同的代码在其他视图中工作时,它不能在此类中工作。我究竟做错了什么?以下是有问题的代码和我日志的屏幕截图......
NSFetchRequest *request26 = [[NSFetchRequest alloc] init];
[request26 setEntity:entityDiscription];
[request26 setResultType:NSDictionaryResultType];
NSExpression *keyPathExpression26 = [NSExpression expressionForKeyPath:@"date"];
NSExpression *swimLast750Expression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression26]];
NSExpressionDescription *expressionDescription26 = [[NSExpressionDescription alloc] init];
[expressionDescription26 setName:@"swimLast750"];
[expressionDescription26 setExpression:swimLast750Expression];
[expressionDescription26 setExpressionResultType:NSInteger16AttributeType];
[request26 setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription26]];
NSPredicate *pred26 = [NSPredicate predicateWithFormat:@"(date >= %@) AND (sport like %@) AND (sessiontype like %@)", swimSinceDateAsDate, sportTypeSwim, sessType1];
[request26 setPredicate:pred26];
NSError *error26;
NSArray *objects26 = [context executeFetchRequest:request26 error:&error26];
if (objects26 == nil) {
NSLog(@"The fetch request returned an array == nil");
} else {
NSLog(@"Contents of Array Object26 is:%@", objects26);
NSDate *sessDate = [[objects26 objectAtIndex:0] valueForKey:@"swimLast750"];
NSLog(@"NSDate is: %@", sessDate);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MMM-yyyy"];
NSLog(@"DATE FORMATTER: %@", [formatter stringFromDate:[[objects26 objectAtIndex:0] valueForKey:@"swimLast750"]]);
NSString *dateString = [formatter stringFromDate:sessDate];
//NSString *dateString = [formatter stringFromDate:[[objects26 objectAtIndex:0] valueForKey:@"swimLast750"]];
NSLog(@"dateString is: %@", dateString);
sw750Last = dateString;
}
答案 0 :(得分:4)
您已设置
[expressionDescription26 setExpressionResultType:NSInteger16AttributeType];
导致获取请求将日期作为NSNumber
返回。
这个数字是自2001年1月1日格林尼治标准时间“参考日期”以来的秒数,
所以你可以将其转换为NSDate
NSNumber *sessDateAsNumber = [[objects26 objectAtIndex:0] valueForKey:@"swimLast750"];
NSDate *sessDate = [NSDate dateWithTimeIntervalSinceReferenceDate:[sessDateAsNumber doubleValue]];
但更好的解决方案可能是使用
[expressionDescription26 setExpressionResultType:NSDateAttributeType];
在表达式描述中。
然后,日期将作为NSDate
对象返回,stringFromDate
按预期工作。
答案 1 :(得分:1)
你必须使用下面的代码将时间戳转换为日期。我想你会把它作为NSNumber得到它,所以你必须在之前将它转换成双值
NSTimeInterval interval = [sessDate doubleValue];
NSDate *swimLast750=[NSDate dateWithTimeIntervalSince1970:interval];
答案 2 :(得分:0)
首先,您需要更改到目前为止的时间间隔,然后设置指定的格式。请尝试以下代码: -
NSDate *date=[NSDate dateWithTimeIntervalSinceReferenceDate:402663864];
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSLog(@"%@",date);
NSString *dateString=[formatter stringFromDate:date];
NSLog(@"dateString=%@",dateString);