0

我有一些简单的代码应该转换我从 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;
}

NSLog 输出

4

3 回答 3

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预期工作。

于 2013-10-25T06:53:40.620 回答
1

您必须使用以下代码将时间戳转换为日期。我认为您会将其作为 NSNumber 获取,因此您必须先将其转换为双精度值

NSTimeInterval interval = [sessDate doubleValue];
NSDate *swimLast750=[NSDate dateWithTimeIntervalSince1970:interval];
于 2013-10-25T05:54:07.520 回答
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);
于 2013-10-25T09:11:36.903 回答