核心数据从本周获取数据 [英] core data get data from current week
本文介绍了核心数据从本周获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个核心数据上下文,对象中存储了日期。我想获取的当前周(星期一到星期日)的数据按顺序。我不是在寻找最近7天。
I have a core data context with objects that have a date stored in them. I would like to get the data for only the current week (Monday to Sunday) in that order. I am not looking for the last 7 days.
日期可以是实体中存储的日期,也可以是将对象添加到核心数据时的日期(它们相同)。
The date could be the one stored inside the entity or the data of when the object was added to core data (they are the same).
我可以使用具有开始日期和结束日期的谓词,如下所示:
I can use a predicate with a start date and end date like this:
NSPredicate *weekPredicate = [NSPredicate predicateWithFormat:@"((date > %@) AND (date <= %@)) || (date = nil)",startDate,endDate];
但是如何计算startDate和endDate?
but how do I calculate startDate and endDate?
-(NSDate *) lastMondayBeforeDate:(NSDate*)timeStamp {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps =
[gregorian components:NSWeekdayCalendarUnit fromDate:timeStamp];
NSInteger weekday = [comps weekday];
weekday = weekday==1 ? 6 : weekday-2; // start with 0 on Monday rather than 1 on Sunday
NSTimeInterval secondsSinceMondayMidnight =
(NSUInteger) [timeStamp timeIntervalSince1970] % 60*60*24 + weekday * 60*60*24;
return [timeStamp dateByAddingTimeInterval:-secondsSinceMondayMidnight];
}
-(NSDate *) nextMondayAfterDate:(NSDate*)timeStamp {
return [[self lastMondayBeforeDate:timeStamp]
dateByAddingTimeInterval:60*60*24*7];
}
这篇关于核心数据从本周获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文