计算一个月的结束或最后一秒

epo*_*gee 5 cocoa objective-c nsdate nscalendar nsdatecomponents

我有最简单的任务,我无法弄清楚如何正确地做.通过下面的代码片段,我可以找到一个月的开头.

NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *beginning = nil;
[cal rangeOfUnit:NSMonthCalendarUnit startDate:&beginning interval:NULL forDate:self];
return beginning;
Run Code Online (Sandbox Code Playgroud)

现在我想确定同一个月的结束(23:59:59的最后一秒适合我的目的).我的第一个想法是在下个月的第一天开始并减去一秒钟.但我无法将NSDateComponent实例中的日期分解为[dateComponents setMonth:[dateComponents month] + 1],因为在12月的情况下,该方法不会接受12 + 1 = 13来到1月,对吗?

那我怎么能到达一个月的最后一秒呢?

spa*_*unt 3

执行此操作以获得下个月的月初:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setMonth:1];
NSDate *beginningOfNextMonth = [cal dateByAddingComponents:comps toDate:beginning options:0];
[comps release];
Run Code Online (Sandbox Code Playgroud)