如何确定两个 NSDate 相隔 1 周?

发布于 2024-10-20 08:09:55 字数 212 浏览 6 评论 0原文

我的应用程序有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南冥有猫 2024-10-27 08:09:56

您可以按日期对条目进行排序(例如按升序)。之后,您可以计算所有后续日期之间的天数差异,基本上是 diff[n] = dayDiff(dates[n], dates[n-1])。因此,对于每个 dates[n],您可以相当快地找到 7 天后的日期 - 只需将 ndiff 相加,直到到达末尾array(=> 没有这样的日期)或者 sum 等于 7(=> 你找到了)或者 sum 大于 7(=> 没有这样的日期)。

不要尝试使用毫秒或类似的东西来获得天数的差异。从某个参考点来看,日期远不止毫秒。为此使用 NSCalendar

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

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;
月隐月明月朦胧 2024-10-27 08:09:56

看看如何使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文