开发者

how to determine when two NSDates are 1 week apart?

开发者 https://www.devze.com 2023-02-14 23:48 出处:网络
I\'m my app I have an NSMutableArray, and each entry has an NSMutableD开发者_如何学JAVAictionary with several Key-Value pairs. One of these pairs contains the date of the entry. For one of the functio

I'm my app I have an NSMutableArray, and each entry has an NSMutableD开发者_如何学JAVAictionary with several Key-Value pairs. One of these pairs contains the date of the entry. For one of the functions of my app I need to determine which entries are exactly 1 week apart from each other (i.e from Sunday to Sunday) and sum the data from one of the Key-Value pairs for each day of that week.

How should I go about doing this?

Note: By Sunday to Sunday I mean just Sunday in general and not exactly say sunday at 9PM to Sunday at 9PM.


See Number of days between two NSDates


You can sort your entries by date (in ascending order for example). After that you can calculate difference in days between all subsequent dates, basically diff[n] = dayDiff(dates[n], dates[n-1]). Therefore for each dates[n] you can find a date 7 days from it quite fast - just sum diffs from n until you reach end of array (=> there is no such date) OR sum is equal to 7 (=> you found it) OR sum is bigger than 7 (=> there is no such date).

Don't try to use milliseconds or something like that to get difference in days. Dates are much more than milliseconds from some reference point. Use NSCalendar for this

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *cs = [calendar components:NSDayCalendarUnit 
                                   fromDate:date1
                                     toDate:date2
                                    options:0];
NSInteger diffInDays = cs.days;


Have a look at using NSDateComponents. You could convert both dates A and B into just their day components, then check for a difference of 7.

0

精彩评论

暂无评论...
验证码 换一张
取 消