2016-10-28 1 views
4

나는이 문제를 가지고 있으므로 여기에 적절한 답을 찾지 못했습니다. 그래서 여기에 작은 자습서를 남겨 둘 것입니다.오늘 데이터로 코어 데이터 조건부 필터

목표는 가져온 개체를 오늘 날짜로 필터링하는 것입니다.

참고 : 스위프트 3과 호환됩니다.

당신은 단순히 오늘 날짜로 날짜를 비교하는 데 사용할 수 없습니다
+0

Pre-Swift 3 질문 및 답변 : http://stackoverflow.com/questions/35688952/how-fetch-objects-with-nsdate-of-today-using-nspredicate. –

답변

11

: 그것은 가능성이기 때문에 그것은 당신의 날짜가 정확한 비교 날짜는 것을 당신에게 아무것도 표시되지 않습니다

let today = Date() 
let datePredicate = NSPredicate(format: "date == %@", today) 

(너무 초 & 밀리 초 포함)

해결책은 이것이다 :

그것은 단지 보여주는 가장 쉬운 & 짧은 방식으로의
// Get the current calendar with local time zone 
var calendar = Calendar.current 
calendar.timeZone = NSTimeZone.local 

// Get today's beginning & end 
let dateFrom = calendar.startOfDay(for: Date()) // eg. 2016-10-10 00:00:00 
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute],from: dateFrom) 
components.day! += 1 
let dateTo = calendar.date(from: components)! // eg. 2016-10-11 00:00:00 
// Note: Times are printed in UTC. Depending on where you live it won't print 00:00:00 but it will work with UTC times which can be converted to local time 

// Set predicate as date being today's date 
let datePredicate = NSPredicate(format: "(%@ <= date) AND (date < %@)", argumentArray: [dateFrom, dateTo]) 
fetchRequest.predicate = datePredicate 

오늘 날짜가있는 객체.

+5

하루 동안 86400 초를 사용하지 마십시오 (일광 절약 시간 전환을 고려하십시오). 적절한 달력 방법을 사용하십시오. 두 날짜를 배열로 전달하는 것은 잘못되었으므로 시도하고 술어를 인쇄하십시오! –

+1

첫 번째 예제는'NSPredicate (format : "date == Date()")'실제로 * 크래시 *. –

+0

예, 86400 초는 초보적인 구현입니다. 더 나은 솔루션으로 답변을 업데이트하겠습니다. 그리고 배열 알림에 감사드립니다. 인수 배열을 전달할 수 있습니다. 업데이트 된 함수를 사용하면 코드가 제대로 작동합니다. – Lawrence413

관련 문제