如何确定两个 NSDate 相隔 1 周?
我的应用程序有一个 NSMutableArray,每个条目都有一个带有多个键值对的 NSMutableDictionary。其中一对包含条目的日期。对于我的应用程序的功能之一,我需要确定哪些条目彼此相隔正好 1 周(即从星期日到星期日),并对该周每一天的键值对之一的数据求和。
我该怎么做呢?
注意:周日到周日我指的是一般周日,而不是确切地说周日晚上 9 点到周日晚上 9 点。
I'm my app I have an NSMutableArray, and each entry has an NSMutableDictionary 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅两个 NSDate 之间的天数
See Number of days between two NSDates
您可以按日期对条目进行排序(例如按升序)。之后,您可以计算所有后续日期之间的天数差异,基本上是
diff[n] = dayDiff(dates[n], dates[n-1])
。因此,对于每个dates[n]
,您可以相当快地找到 7 天后的日期 - 只需将n
的diff
相加,直到到达末尾array(=> 没有这样的日期)或者 sum 等于 7(=> 你找到了)或者 sum 大于 7(=> 没有这样的日期)。不要尝试使用毫秒或类似的东西来获得天数的差异。从某个参考点来看,日期远不止毫秒。为此使用
NSCalendar
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 eachdates[n]
you can find a date 7 days from it quite fast - just sumdiffs
fromn
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看看如何使用 NSDateComponents。您可以将日期 A 和 B 都转换为它们的日期组成部分,然后检查是否有 7 的差异。
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.