修改NSDate以表示从今天起的1个月 [英] Modifying NSDate to represent 1 month from today

查看:109
本文介绍了修改NSDate以表示从今天起的1个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为正在处理的Cocoa应用程序添加重复事件。我每天和每周都重复,因为我可以定义这些数学(3600 * 24 * 7 = 1周)。我使用下面的代码修改日期:

I'm adding repeating events to a Cocoa app I'm working on. I have repeat every day and week fine because I can define these mathematically (3600*24*7 = 1 week). I use the following code to modify the date:

[NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))]

我知道事件重复后已经过去了多少个月,但我不知道如何使NSDate对象代表未来1个月/ 3个月/ 6个月/ 9个月。理想情况下,我希望用户从10月14日起每月重复,并且每月重复14次。

I know how many months have passed since the event was repeated but I can't figure out how to make an NSDate object that represents 1 month/3 months/6 months/9 months into the future. Ideally I want the user to say repeat monthly starting Oct. 14 and it will repeat the 14th of every month.

推荐答案

此问题相同。 )

文档


使用NSCalendarDate强烈
。它不是过时的,
,但它可能在Mac OS X v10.5之后的下一个主要OS
版本。对于
日历计算,您应该
使用
NSCalendar,NSDate和
的合适组合,如
中所述$ d
日历日期和时间
Cocoa的编程主题

遵循以下建议:

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];

可能有更直接或更有效的实现,但这应该是准确的,方向。

There may be a more direct or efficient implementation, but this should be accurate and should point in the right direction.

这篇关于修改NSDate以表示从今天起的1个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆