NSPredicate由年蛾日筛选 [英] NSPredicate filtered by year moth day

查看:116
本文介绍了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

我需要创建谓词

推荐答案

只要使用此值即可获取我的对象

如果您的日期存储为实际日期,那么您应该使用它的优势,而不是格式化。您可以简单地创建一个谓词,检查日期是否在两个日期(包含时间)之间。第一个日期是您的日期,时间为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天全站免登陆