如何使用NSPredicate使用今天的NSDate获取对象? [英] How fetch objects with NSDate of today using NSPredicate?
问题描述
我的核心数据模型和涉及日期的提取请求陷入了困境.
I'm stuck in a problem with my Core Data model and a fetch request that involves dates.
我在具有NSDate属性的实体中有一些对象;我需要提取日期为今天的对象,但是我总是从以下代码中得到零:
I have some objects in a entity with a NSDate attribute; I need to extract the objects with the date of today but I always get nil from this code:
public func getObjectsOfToday() -> Array<myObject>?
{
let entityDescription = NSEntityDescription.entityForName("Objects", inManagedObjectContext: DataAccess.sharedInstance.managedObjectContext)
let request = NSFetchRequest()
request.entity = entityDescription
request.returnsObjectsAsFaults = false
let today = NSDate()
request.predicate = NSPredicate(format: "(dateStart => %@) AND (dateStart <= %@)", today, today)
var objects: [AnyObject]?
do
{
objects = try DataAccess.sharedInstance.managedObjectContext.executeFetchRequest(request)
}
catch let error as NSError
{
print(error)
objects = nil
}
return objects as? Array<Objects>
}
我认为这是NSPredicate的问题,因为它还考虑了小时,分钟和秒.如果我今天打印的话是这样的:
the problem I think it's the NSPredicate because it considers also hours, minute and seconds. If I print today is something like:
今天的印刷说明:2016-02-28 22:02:01 +0000
Printing description of today: 2016-02-28 22:02:01 +0000
但是我想获取日期相同的对象,而忽略小时,分钟和秒.我该怎么办?
我还尝试使用组件创建另一个NSDate:
I also tried to create another NSDate using components:
let components = cal.components([.Day , .Month, .Year ], fromDate: today)
let newDate = cal.dateFromComponents(components)
但是结果是一样的.我在做什么错了?
but the result it's the same. What am I doing wrong?
推荐答案
我要做的是将它与一天的开始和结束时间进行比较,并具有几个辅助函数来计算它们:
What I do is compare it to the start and end of the day and have a couple helper functions to calculate them:
class DateHelper{
internal class func startOfDay(day: NSDate) -> NSDate {
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let unitFlags: NSCalendarUnit = [.Minute, .Hour, .Day, .Month, .Year]
let todayComponents = gregorian!.components(unitFlags, fromDate: day)
todayComponents.hour = 0
todayComponents.minute = 0
return (gregorian?.dateFromComponents(todayComponents))!
}
internal class func endOfDay(day: NSDate) -> NSDate {
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let unitFlags: NSCalendarUnit = [.Minute, .Hour, .Day, .Month, .Year]
let todayComponents = gregorian!.components(unitFlags, fromDate: day)
todayComponents.hour = 23
todayComponents.minute = 59
return (gregorian?.dateFromComponents(todayComponents))!
}
}
因此,在您的代码中,您将调用:
So in your code, you would call:
request.predicate = NSPredicate(format: "(dateStart => %@) AND (dateStart <= %@)", DateHelper.startOfDay(today), DateHelper.endOfDay(today))
这篇关于如何使用NSPredicate使用今天的NSDate获取对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!