NSPredicate 按年月日过滤 [英] NSPredicate filtered by year moth day

查看:22
本文介绍了NSPredicate 按年月日过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Core Data 来存储我的数据模型对象.每个对象都有 NSDate 属性.

I use Core Data for storing my data model objects. Each object has NSDate property.

NSDate 属性的格式如下:

NSDate property has format like below:

2013-03-18 12:50:31 +0000

我需要创建谓词,无需时间就可以通过这个值 2013-03-18 获取我的对象.

I need to create predicate that will fetch my objects just by this value 2013-03-18 without time.

推荐答案

如果您的日期存储为实际日期,那么您应该充分利用它,而不是摆弄格式.您可以简单地创建一个谓词来检查日期是否在两个日期之间(带时间).第一个日期是您的日期,时间为 00:00:00,第二个日期是之后的一天.

If your dates are stored as actual dates then you should use that to your advantage and not fiddle with formats. You can simply create a predicate that checks that if the dates is between two dates (with times). The first date is your date with the time 00:00:00 and the second date is one day after that.

// Create your date (without the time)
NSDateComponents *yourDate = [NSDateComponents new];
yourDate.calendar = [NSCalendar currentCalendar];
yourDate.year  = 2013;
yourDate.month = 3;
yourDate.day   = 18;
NSDate *startDate = [yourDate date];

// Add one day to the previous date. Note that  1 day != 24 h
NSDateComponents *oneDay = [NSDateComponents new];
oneDay.day = 1;
// one day after begin date
NSDate *endDate = [[NSCalendar currentCalendar] dateByAddingComponents:oneDay 
                                                                toDate:startDate
                                                               options:0];

// Predicate for all dates between startDate and endDate
NSPredicate *dateThatAreOnThatDay = 
    [NSPredicate predicateWithFormat:@"(date >= %@) AND (date < %@)", 
                                     startDate, 
                                     endDate]];

这篇关于NSPredicate 按年月日过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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