【发布时间】:2021-03-25 17:21:19
【问题描述】:
在这里,我使用 NSPredicate 使用 NSFetchRequest 从 Core Data 获取本周星期一的历史记录。我不知道为什么这不起作用,你能帮我吗?我星期四有相同的代码,只是工作日不同,但由于某种原因,它多次打印出日期这是我的代码,我还附上了控制台:
func getDateMonday(){
let currentDate = Date()
let calendar = Calendar.current
let weekOfMonth = calendar.component(.weekOfMonth, from: Date())
let month = calendar.component(.month, from: Date())
let mondayComponentStart = DateComponents(month: month, hour: 0, minute: 0, second: 0, weekday: 2, weekOfMonth: weekOfMonth)
let mondayComponentEnd = DateComponents(month: month, hour: 23, minute: 59, second: 59, weekday: 2, weekOfMonth: weekOfMonth )
let lastMondayStart = Calendar.current.nextDate(after: currentDate,
matching: mondayComponentStart,
matchingPolicy: .nextTime,
repeatedTimePolicy: .first,
direction: .backward) ?? Calendar.current.nextDate(after: currentDate, matching: mondayComponentStart, matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .forward)
let lastMondayEnd = Calendar.current.nextDate(after: currentDate,
matching: mondayComponentEnd,
matchingPolicy: .nextTime,
repeatedTimePolicy: .first,
direction: .forward) ?? Calendar.current.nextDate(after: currentDate, matching: mondayComponentEnd, matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .backward)
let predicateStart = NSPredicate(format: "date >= %@", lastMondayStart! as NSDate)
let predicateEnd = NSPredicate(format: "date <= %@", lastMondayEnd! as NSDate)
let allPredicate = NSCompoundPredicate(type: .and, subpredicates: [predicateStart, predicateEnd])
let waterFetch = NSFetchRequest<Water>(entityName: "Water")
waterFetch.predicate = allPredicate
do {
print(lastMondayStart!)
print(Date())
print(lastMondayEnd!)
print("------------------")
let waterF = try viewContext.fetch(waterFetch)
for all in waterF {
let tot = all.amount
monday += Int(tot)
Total += Int(tot)
}
} catch {
}
}
【问题讨论】:
-
3 月第 4 周的下周一 (
lastMondayEnd) 是 2022 年。将DateComponents(day: 1, second: -1)添加到开始日期或在开始日期之后查找23:59:59更容易跨度> -
感谢您的帮助,但是您知道为什么星期四会在控制台中出现两次吗,因为如果我删除它,它将是另一天出现两次,特别是总是从后面第三次出现。
-
2022 年有几个日期没有意义。检查您的设计。
标签: swift core-data nspredicate