我正在向我正在开发的 Cocoa 应用程序添加重复事件。我每天和每周都会重复,因为我可以用数学方式定义这些(3600*24*7 = 1 周)。我使用以下代码来修改日期:
[NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))]
我知道自从事件重复以来已经过去了多少个月,但我不知道如何制作一个代表未来 1 个月/3 个月/6 个月/9 个月的 NSDate 对象。理想情况下,我希望用户说从 10 月 14 日开始每月重复,并且它将在每个月 14 日重复。
(几乎与这个问题 https://stackoverflow.com/questions/181459/is-there-a-better-way-to-find-midnight-tomorrow/181495#181495.)
来自文档 http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html:
强烈使用 NSCalendarDate
灰心。它还没有被弃用,
但它可能会出现在下一个主要操作系统中
Mac OS X v10.5 之后发布。为了
日历计算,你应该
使用合适的组合
NSCalendar、NSDate 和
NSDateComponents,如中所述
日历在日期和时间
Cocoa 编程主题 http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html.
遵循该建议:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];
NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth];
NSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today];
nextMonthComponents.day = todayDayComponents.day;
NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];
[gregorian release];
可能有更直接或更有效的实施,但这应该是准确的并且应该指向正确的方向。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)