核心数据谓词日期比较 [英] Core Data Predicate Date Comparison

查看:133
本文介绍了核心数据谓词日期比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取一个实体匹配一个用户selectedDate(它是一个NSDate)的所有对象。
Core Data代码很好,但是我的谓词一直返回0个结果,日期在用户选择的数据库中是一样的。

Im trying to fetch all the objects in an entity matching a user selectedDate (it's an NSDate). The Core Data code is fine but my predicate keeps returning 0 results, the dates are the same in the database as the user is selecting.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(eDate = %@)", selectedDate];


推荐答案

您的谓词看起来很好。

然而,返回零结果的原因可能是日期不完全相同。

The reason you're finding zero result are returned however may be that the dates aren't entirely the same.

例如:

05/04/2012 13:37:00 05/04/2012 13:37:01 不匹配,因为这两个值不完全相同。

05/04/2012 13:37:00 will not match with 05/04/2012 13:37:01 as these two values are not exactly the same.

您要检查日期(日,月,年)以及时间吗?

Do you want to check the date (day, month, year) as well as the time?

如果您只想检查日期,则应创建开始日期和结束日期,并使用用户选择的日期作为参考框架进行比较。

If you only want to check the date, you should create a start date and end date and compare them using the user selected date as a frame of reference.

与此类似的内容应该为00:00:00创建日期和时间。

Something similar to this should create a date and time for 00:00:00.

//gather current calendar
NSCalendar *calendar = [NSCalendar currentCalendar];

//gather date components from date
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];

//set date components
[dateComponents setHour:0];
[dateComponents setMinute:0];
[dateComponents setSecond:0];

//return date relative from date
return [calendar dateFromComponents:dateComponents];

通过将小时,分钟和秒设置为23:59:59来创建另一个日期,

Create another date by setting the hours, minutes and seconds to 23:59:59 and check that your user selected date falls between these ranges.

[NSPredicate predicateWithFormat:@"date BETWEEN %@", [NSArray arrayWithObjects:startOfDay, endOfDay, nil]]

这篇关于核心数据谓词日期比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆